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?
Process(m I) intis not elegant ?func Process(m I) int { … }seems to be the way to go. play.golang.org/p/t59t5KHlw6 .