考虑这段代码:
type Rectangle struct {
Width, Height, Area int
}
type Square struct {
Side, Area int
}
type Geometry struct {
Area int
}
func SumGeometries(geometries ...Geometry) (sum int) {
for _, g := range geometries {
sum += g.Area
}
return
}
func TestSumGeometries(t *testing.T) {
rect := Rectangle{5, 4, 20}
square := Square{5, 25}
got := SumGeometries(rect, square) // cannot use rect (variable of type Rectangle) as Geometry value in argument to MyFunc compilerIncompatibleAssign
want := 45
if got != want {
t.Error("fail!")
}
}
我希望 MyFunc 采用包含 Apple 的任何结构,而不仅仅是特定的 BStruct。
这在 Go 中可以实现吗?
我能找到 ATM 的唯一方法如下:
type Rectangle struct {
Width, Height, Area int
}
func (r *Rectangle) GetArea() int {
return r.Area
}
type Square struct {
Side, Area int
}
func (s *Square) GetArea() int {
return s.Area
}
type Areaer interface {
GetArea() int
}
func SumGeometries(geometries ...Areaer) (sum int) {
for _, s := range geometries {
sum += s.GetArea()
}
return
}
func TestArgs(t *testing.T) {
rect := Rectangle{5, 4, 20}
square := Square{5, 25}
got := SumGeometries(&rect, &square) // cannot use rect (variable of type Rectangle) as Geometry value in argument to MyFunc compilerIncompatibleAssign
want := 45
if got != want {
t.Error("fail!")
}
}
感觉可能不符合习惯:当我已经对消费者直接访问数据感到满意时,我是否想用不必要的方法污染我的结构?
忽然笑
相关分类