1

Trying to understand the blank functionality of interface in go.

type Manager interface {
    GetAge(name string) (int, error)
}

type manager struct {
}

var _ Manager = &manager{}

func NewManager() Manager {
    return &manager{}
}
ryan
  • 974
  • 2
  • 7
  • 13
  • 1
    Possible duplicate of http://stackoverflow.com/questions/38167403/specs-whats-the-purpose-of-the-blank-identifier-in-variable-assignment – Charlie Tumahai Aug 18 '16 at 21:42

1 Answers1

2

This is a particular idiom used to assert at compile time whether a concrete type implements a given interface.

In the above code, if the person writing the manager type forgets to implement a GetAge method for it, the code won't compile, and the compilation error will tell them exactly which methods are missing.

It may appear a bit redundant here, but if the interface required to be implemented by a type has a large number of methods, this technique may be helpful.

Note that because of the above reasons, the code above won't compile. Also, you need to make sure, give that &manager{} is used in the blank declaration, that it's *manager (pointer to manager) that implements the Manager interface, and not simply manager.

abhink
  • 8,740
  • 1
  • 36
  • 48