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?
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.