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?
Go Interfaces are implemented implicitly Unlike other languages like Java, you don't need to explicitly specify that a type implements an interface using something like an implements keyword. You just implement all the methods declared in the interface and you're done.
interface{} is the Go empty interface, a key concept. Every type implements it by definition. An interface is a type, so you can define for example: type Dog struct { Age interface{} }
A type implements an interface by implementing its methods. There is no explicit declaration of intent, no "implements" keyword. Implicit interfaces decouple the definition of an interface from its implementation, which could then appear in any package without prearrangement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With