Go - how to explicitly state that a structure is implementing an interface?

Method 2 is the correct one, method 1 you're just embedding a type and overriding its function. If you forget to override it, you will end up with a nil pointer dereference.


I have rarely needed to declare this, because there is almost always somewhere in my package where I am using the struct as the interface. I tend to follow the pattern of keeping my structs unexposed where possible, and providing them only through "constructor" functions.

type Foo interface{
  Foo()
}

type bar struct {}
func (b *bar)Foo() {}

func NewBar() Foo{
  return &bar{}
}

If bar does not satisfy Foo, this will not compile. Rather than add constructs to declare that the type implements the interface, I just make sure that my code uses it as the interface at some point.