Compile time checks to ensure your type satisfies an interface #golang #quicktip

// for pointers to struct
type MyType struct{}
var _ MyInterface = (*MyType)(nil)
// for struct literals
var _ MyInterface = MyType{}
// for other types - just create some instance
type MyType string
var _ MyInterface = MyType("doesn't matter")

The above snippets specify that `MyType` must be assignable, and therefore said to satisfy the `MyInterface` interface.

Since the variable is named an underscore, it will not be kept around and won’t take up any memory.

If you forget a method or if the interface changes, you’ll get a compile-time error drawing your attention to it immediately:

cannot use (*MyType)(nil) (type *MyType) as type MyInterface in assignment:
*MyType does not implement MyInterface (missing SomeMethod method)

Essentially you are casting `nil` to a type of pointer to `MyType`. It’s a zero-memory way to represent a pointer to your struct in Go.

--

--

Founder at MachineBox.io — Gopher, developer, speaker, author — BitBar app https://getbitbar.com — Author of Go Programming Blueprints

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mat Ryer

Founder at MachineBox.io — Gopher, developer, speaker, author — BitBar app https://getbitbar.com — Author of Go Programming Blueprints