Check if the structure implements an interface in Go

There are two options for checking: at compile time and in runtime.

At compile time

To check interface methods implementation, you can use typed nil.

var _ Interface = (*Type)(nil)

It does not contain any data by itself, it does not require allocation, but it has a type that can be read and used.

type Animal interface {
	GetName()
}

var _ Animal = (*Cat)(nil)
type Cat struct {
	string name
}

If the structure does not implement interface methods, an error will occur when trying to run such code.

./prog.go:11:16: cannot use (*Cat)(nil) (value of type *Cat) as type Animal in variable declaration: *Cat does not implement Animal (missing GetName method)

https://go.dev/play/p/dmx37JJZnmT

In Runtime:

Use a type assertion.

The type assertion x.(T) asserts that the particular value stored in x is of type T and that x is not nil.

  • If T is not an interface, it asserts that the dynamic type x is identical to T.
  • If T is an interface, it asserts that the dynamic type x implements T.
_, ok = interface{}(Cat{}).(Animal)

https://go.dev/play/p/S4AyInpBTPO