This question already has an answer here:
I faced a strange behavior in Go structs. I might be misunderstanding something but when I created like so:
type ITest interface {
Foo() string
Bar(string)
}
type Base struct {
value string
}
func (b Base) Foo () string {
return b.value
}
func (b *Base) Bar (val string) {
b.value = val
}
// Not implementing ITest
type Sub struct {
Base
}
// Now it works
type Sub struct {
*Base
}
Then Sub
is not implementing ITest
. But if I change Sub
to embed pointer of Base
it starts to implement ITest
. I know it somehow related to caller in methods but come on. So the question is: Is that me Going wrong or Go have problems with embedding logic?
</div>
*Base
has a method Bar
, but Base
does not; so Base
does not implement ITest
. Thus, embedding a *Base
allows Sub
to implement the interface.
Your use of the names Base
and Sub
also implies you may be conflating composition and inheritance, which you should be very careful with in Go. There is no inheritance in Go. There are no base classes, no subclasses, no class hierarchy, no inheritance. The only form of polymorphism in go is interfaces.