0

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Hordii
  • 159
  • 1
  • 7
  • 1
    See [X does not implement Y (… method has a pointer receiver)](https://stackoverflow.com/questions/40823315/x-does-not-implement-y-method-has-a-pointer-receiver/40824044#40824044) (2nd part of the answer: Structs and embedding). Also: [Why does this Type Assertion on a direct implemented interface fail?](https://stackoverflow.com/questions/52739991/why-does-this-type-assertion-on-a-direct-implemented-interface-fail) – icza Oct 16 '18 at 14:25
  • You ca use both the implementations of Sub but you need to use a pointer in the first case. For example https://play.golang.org/p/1zPXfsJacBt – Massimo Zerbini Oct 16 '18 at 14:44

1 Answers1

1

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

Adrian
  • 42,911
  • 6
  • 107
  • 99