英文:
Define method on multiple structs that implement the same interface
问题
请问您需要将这段代码翻译成中文吗?
英文:
Take the following piece of code:
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()
}
Methods cannot be defined on interfaces so m
cannot be of type I
. I tried using anonymous fields on A
and B
but Attr
is specific to the associated structs so it can't be implemented on an anonymous field.
I want to avoid copy/pasting the Process()
method on A
and B
since it is exactly the same. I could simply define
func Process(m I) int { … }
instead but it's not very elegant.
How would you go about doing this the go way?
答案1
得分: 2
在Go语言中,目前无法实现这个功能。虽然你可以通过在结构体中嵌入另一个类型来为多个类型引入公共方法,但这些方法对于被嵌入的类型并没有意识。
在这种情况下,通常的Go语言惯用法是使用函数。以标准库中的sort
包为例,它定义了一个接口,其中包含实现容器排序算法所需的方法(Len
、Less
和Swap
)。然而,实际的排序算法作为一个函数公开,该函数接受实现该接口的参数。
英文:
This is not currently possible in Go. While you can introduce common methods to a number of types via embedding another type within a struct, those methods have no knowledge of the type they have been embedded in.
The usual Go idiom for this pattern is to use a function. As an example, sort
package from the standard library. It defines an interface consisting of the methods needed to implement a sort algorithm on a container (Len
, Less
, and Swap
). However, the actual sort algorithm is exposed as a function that takes an argument implementing the interface.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论