[Golang] Compile type assertion

Tags
Golang
Engineering
Created
Nov 8, 2023 04:12 AM
Edited
Nov 7, 2023
Description

What

It is a way to examine if your type has the methods that the interface your type implements.
// var _ AnInterface = YourType

// From https://medium.com/@matryer/golang-tip-compile-time-checks-to-ensure-your-type-satisfies-an-interface-c167afed3aae
// 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")

When missing a method for an interface

cannot use (*MyType)(nil) (type *MyType) as type MyInterface in assignment:

- MyType does not implement MyInterface (missing SomeMethod method)

Why

It is useful to do a type check or to see if your type has the necessary methods. This is very useful in a large codebase, and you can see the error directly from the IDEs.

Source