我正在经历An Introduction to Programming in Go并尝试掌握界面。我觉得我对它们是什么以及我们为什么需要它们有所了解但是我在使用它们时遇到了麻烦。在他们的部分结束时
接口也可以用作字段:
type MultiShape struct { shapes []Shape }
我们甚至可以通过给它一个区域方法将MultiShape本身变成一个Shape:
func (m *MultiShape) area() float64 { var area float64 for _, s := range m.shapes { area += s.area() } return area }
现在,MultiShape可以包含圆形,矩形甚至其他MultiShapes。
我不知道如何使用它。我对此的理解是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背景,所以如果两者之间有某种联系会有所帮助。
由于
答案 0 :(得分:2)
例如,
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
}
type Rectangle struct {
x1, y1, x2, y2 float64
}
func (s *Rectangle) area() float64 {
x := math.Abs(s.x2 - s.x1)
y := math.Abs(s.y2 - s.y1)
return x * y
}
func (s *Rectangle) distance() float64 {
x := s.x2 - s.x1
y := s.y2 - s.y1
return math.Sqrt(x*x + y*y)
}
type Circle struct {
x, y, r float64
}
func (s *Circle) area() float64 {
return math.Pi * s.r * s.r
}
func main() {
r1 := Rectangle{1, 1, 4, 4}
fmt.Println(r1.area())
r2 := Rectangle{2, 4, 3, 6}
fmt.Println(r2.area())
c := Circle{10, 10, 2}
fmt.Println(c.area())
m := MultiShape{[]Shape{&r1, &r2, &c}}
fmt.Println(m.area())
}
输出:
9
2
12.566370614359172
23.566370614359172