www dot mike e e dot net

a little peace of mind

go doesn’t give a way to explicitly say that a struct should implement an interface. this isn’t really a problem…. if you try to use a struct that doesn’t implement the correct interface, you do indeed get an error:

 1type ExampleInterface interface {
 2	doSomething(input string) error
 3}
 4
 5type exampleStruct struct{}
 6
 7func useInterface(x ExampleInterface) {
 8	x.doSomething("hello")
 9}
10
11func main() {
12	inst := exampleStruct{}
13	useInterface(inst) // ... exampleStruct does not implement ExampleInterface (missing method doSomething)
14}

sometimes though I know I want my type to implement some interface before I’ve ever consumed it (don’t yell at me for this)

something to document that a struct should implement an interface in the code, but have it be more……..

sturdy?

i stumbled across something for this online a while back and have been using it here and there since:

1var _ ExampleInterface = (*exampleStruct)(nil)

this allows you to declare that interface implementation and let the compiler throw an error at you until you’ve done it, before you’ve even tried to use the struct.

1type ExampleInterface interface {
2	doSomething(input string) error
3}
4
5type exampleStruct struct{}
6// *exampleStruct does not implement ExampleInterface (missing method doSomething)
7var _ ExampleInterface = (*exampleStruct)(nil)
8

this is especially handy if you have goimpl, vscode will give you a quick-action on the error to generate stubs for the interface on your struct.