Go - how to explicitly indicate that a struct implements an interface?

Since Go places a lot of emphasis on interfaces, I am wondering how I can explicitly state that a struct implements an interface for clarity and error checking in the absence of a method? I have seen two approaches so far and I am wondering which is correct and consistent with the 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 these methods correct or is there some other way to do something like this?

+3


source to share


3 answers


Method 2 is correct, method 1 you just insert the type and override its function. If you forget to redefine it, you end up spinning the pointer to zero.



+8


source


You can not. In Go, all interface implementations are implicit. You can check if the type and interface implements (the most explicit it gets). If I remember correctly in a project I was working on, it just stated that the top of the package asserts the interface type with the interfaces that were implemented, as close to explicit as it gets.



+1


source


I've rarely needed to declare this, because it's almost always somewhere in my package where I use struct as an interface. I tend to follow the pattern of keeping my structures, if possible, and only exposing them through "constructor" functions.

type Foo interface{
  Foo()
}

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

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

      

If bar

not Foo

, it won't compile. Instead of adding constructs that declare that a type implements an interface, I just make sure my code uses it as an interface at some point.

+1


source







All Articles