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