Go 在实现同一接口的多个结构上定义方法
以下面的代码为例:Go 在实现同一接口的多个结构上定义方法,go,Go,以下面的代码为例: type A struct { … } func (a *A) Attr() int { … } type B struct { … } func (b *B) Attr() int { … } type I interface{ Attr() int } func (m that implements I) Process() int { do something with m.Attr() } func main() { a := A{} a.Pr
type A struct { … }
func (a *A) Attr() int { … }
type B struct { … }
func (b *B) Attr() int { … }
type I interface{
Attr() int
}
func (m that implements I) Process() int {
do something with m.Attr()
}
func main() {
a := A{}
a.Process()
b := B{}
b.Process()
}
无法在接口上定义方法,因此m
不能是I
类型。我尝试在A
和B
上使用匿名字段,但是Attr
特定于关联的结构,因此无法在匿名字段上实现
我希望避免在A
和B
上复制/粘贴Process()。我可以简单地定义
func Process(m I) int { … }
但是它不是很优雅
您将如何以围棋的方式进行此操作?这在围棋中目前是不可能的。虽然可以通过在结构中嵌入另一个类型来为许多类型引入公共方法,但这些方法不知道它们嵌入的类型
此模式的常用Go习惯用法是使用函数。例如,来自标准库。它包括在容器上实现排序算法所需的方法(Len
、Less
和Swap
)。然而,实际的排序算法需要一个参数来实现接口。为什么Process(mi)int
并不优雅?采用接口的函数是实现它的惯用方法。一切都不必像其他一些OOP语言(例如Ruby)中的方法一样。是的,我想我必须摆脱我的OO反射;-)我同意func-Process(mi)int{…}
似乎是应该走的路。