Search code examples
inheritancegointerfacestandards

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


Since Go puts a heavy emphasis on interfaces, I'm wondering how can I explicitly state that a structure is implementing an interface for clarity and errors checking in case some method is missing? I have seen two approaches so far, and I'm wondering which is correct and in accordance to Go specification.

Method 1 - anonymous field

type Foo interface{
    Foo()
}

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

Method 2 - Explicit conversion

type Foo interface{
    Foo()
}

type Bar struct {
}
func (b *Bar)Foo() {
}
var _ Foo = (*Bar)(nil)

Are those methods correct, or is there some other way to do something like this?


Solution

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