2
我正在通過An Introduction to Programming in Go並試圖掌握接口。我覺得我對他們是什麼以及爲什麼需要他們有一個確定的想法,但我無法使用他們。在本節結束時,他們有GO使用接口作爲字段
接口也可以用來作爲字段:
type MultiShape struct { shapes []Shape }
我們甚至可以將MultiShape自己變成一個形狀給它的面積法:
func (m *MultiShape) area() float64 { var area float64 for _, s := range m.shapes { area += s.area() } return area }
現在MultiShape可以包含圓形,矩形或其他多種形狀。
我不知道如何使用它。我對此的理解是MultiShape
可以有Circle
和Rectangle
在它的slice
這是示例代碼我與
package main
import ("fmt"; "math")
type Shape interface {
area() float64
}
type MultiShape struct {
shapes []Shape
}
func (m *MultiShape) area() float64 {
var area float64
for _, s := range m.shapes {
area += s.area()
}
return area
}
// ===============================================
// Rectangles
type Rectangle struct {
x1, y1, x2, y2 float64
}
func distance(x1, y1, x2, y2 float64) float64 {
a := x2 - x1
b := y2 - y1
return math.Sqrt(a*a + b*b)
}
func (r *Rectangle) area() float64 {
l := distance(r.x1, r.y1, r.x1, r.y2)
w := distance(r.x1, r.y1, r.x2, r.y1)
return l*w
}
// ===============================================
// Circles
type Circle struct {
x, y, r float64
}
func (c * Circle) area() float64 {
return math.Pi * c.r*c.r
}
// ===============================================
func totalArea(shapes ...Shape) float64 {
var area float64
for _, s := range shapes {
area += s.area()
}
return area
}
func main() {
c := Circle{0,0,5}
fmt.Println(c.area())
r := Rectangle{0, 0, 10, 10}
fmt.Println(r.area())
fmt.Println(totalArea(&r, &c))
//~ This doesn't work but this is my understanding of it
//~ m := []MultiShape{c, r}
//~ fmt.Println(totalArea(&m))
}
工作有人可以幫助我?我有一個python背景,所以如果兩者之間有某種聯繫會有所幫助。
感謝
我有那麼多,我沒有得到這個角色是'MultiShape'。 – Jeff
:P對不起,我以爲你做完了 – Jeff
現在就來看看。 – peterSO