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)

What on earth does `(*MyType)(nil)` mean?

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.