One of the things I love about Go and find to be a strong supporter of serendipitous interface standardization is Go’s implicitly declared interfaces.
However, there are times you really, really want to explicitly declare an interface, such as when you have a larger interface and you want your IDE and/or the compiler to tell you when you are not implementing it correctly.
This was my situation when I was brand new to go and given the fact that go did not have an implement
keyword or similar I just assumed that you could not explicitly declare an interface.
So I did what any frustrated developer would do and I blogged to request a new language feature[1]. And lo-and-behold, someone explained that which google had failed me. And so I am blogging about it today in hopes that other Go-newbies won’t miss this wonderful technique.
Simply put, define a variable using the blank identifier of the type of your interface, and then assign a nil pointer of your struct’s type to that blank variable, and voila, you now have explicitly defined your that your struct implements your interface:
var _ Gearboxer = (*Gearbox)(nil)
type Gearboxer interface {
Start(BoxArgs) error
Stop(BoxArgs) error
...
}
type Gearbox struct {
Config Config
Api api.Api
...
}
func (me *Gearbox) Start(args BoxArgs) error {
...
}
func (me *Gearbox) Stop(args BoxArgs) error {
...
}
...
[1] Actually, my feature request was more than just explicit interface declarations, but it was during that discussion that I learned how to declare them.)