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?
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.
You cannot. In Go all interface implementations are implicit. You can check if a type implements and interface (the most explicit it gets). If I recall correctly in a project I worked in it just did some type asserts at the top of the package against the interfaces which the type implemented, as close to explicit as it gets.
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.