Sobes.tech
Senior

What does the construction `var _ Interface = (*Type)(nil)` mean in Go?

sobes.tech AI

Answer from AI

The construction var _ Interface = (*Type)(nil) in Go is used for compile-time checking that the type *Type implements the Interface interface.

Explanation:

  • (*Type)(nil) is a nil pointer to the type Type.
  • Assigning it to a variable of type Interface makes the compiler verify whether *Type implements all the methods of the interface.
  • The variable named _ is an anonymous variable, which is not used, so the code does not occupy memory.

This is a kind of static assert that helps prevent errors if the interface or type changes and the implementation ceases to satisfy the interface.

Example:

type Reader interface {
    Read(p []byte) (n int, err error)
}

type MyReader struct {}

func (r *MyReader) Read(p []byte) (int, error) {
    return 0, nil
}

var _ Reader = (*MyReader)(nil) // Check implementation of Reader interface

If MyReader does not implement Read, the compiler will produce an error.