Go

What does var _ io.Writer = (*MyWriter)(nil) do, and why is it used?

Question 93MediumGo 1.22 to 1.25

It is a compile-time assertion that *MyWriter implements io.Writer. Go interfaces are satisfied implicitly, so if someone changes a method signature, the type silently stops implementing the interface. Usually the error then shows up far away, at some call site, or never shows up if the only use is a dynamic type assertion.

type MyWriter struct{}

func (w *MyWriter) Write(p []byte) (int, error) { return len(p), nil }

// Compile-time checks (zero runtime cost, nothing allocated):
var _ io.Writer = (*MyWriter)(nil)   // pointer type implements it
var _ fmt.Stringer = Celsius(0)      // value type implements it

// If Write changes to Write(p []byte) error, the build fails here:
// cannot use (*MyWriter)(nil) (value of type *MyWriter) as io.Writer value in variable declaration:
// *MyWriter does not implement io.Writer (wrong type for method Write)

Why this form works:

  • (*MyWriter)(nil) is a typed nil pointer, so no value gets constructed.
  • The blank identifier _ means the variable is never used or stored, so the compiler optimizes it away.

Use it when satisfying the interface is part of the type's contract but nothing in the package exercises it statically. Plugin registrations, types consumed only through reflection or type assertions, and http.Handler implementations are common cases. The standard library and large codebases such as Kubernetes use it widely.

More on Interfaces, Methods & Embedding

All 35 Interfaces, Methods & Embedding questions