I want to provide a base struct with methods in my library that can be 'extended'.
The methods of this base struct rely on methods from the extending struct. This is not directly possible in Go, because struct methods only have acces to the structs own fields, not to parent structs.
The point is to have functionality that I do not have to repeat in each extending class.
I have come up with this pattern, which works fine, but looks quite convoluted due to it's cyclical structure.
I have never found anything like it in other Go code. Is this very un-go? What different approach could I take?
type MyInterface interface {
SomeMethod(string)
OtherMethod(string)
}
type Base struct{
B MyInterface
}
func (b *Base) SomeMethod(x string) {
b.B.OtherMethod(x)
}
type Extender struct {
Base
}
func (b *Extender) OtherMethod(x string) {
// Do something...
}
func NewExtender() *Extender {
e := Extender{}
e.Base.B = &e
return &e
}