在多个实现相同接口的结构体上定义方法。

huangapple go评论89阅读模式
英文:

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为例,它定义了一个接口,其中包含实现容器排序算法所需的方法(LenLessSwap)。然而,实际的排序算法作为一个函数公开,该函数接受实现该接口的参数。

英文:

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.

huangapple
  • 本文由 发表于 2014年12月13日 05:30:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/27452427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定