Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 808
ThePiachu Avatar asked Jul 31 '15 18:07

ThePiachu


People also ask

How are interfaces implemented in Go?

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.

What is interface {} GoLang?

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{} }

Why are Go interfaces implicit?

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.


1 Answers

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.

like image 161
OneOfOne Avatar answered Sep 29 '22 14:09

OneOfOne