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
- Q91Why would you embed an interface inside a struct? What is the danger?
- Q92When should you use
any(interface{}), and when are generics the better choice? - Q94Go interfaces are satisfied implicitly. What design consequences follow, and where should interfaces be defined?
- Q95Explain "accept interfaces, return structs". When is returning an interface justified?
- Q96Why does Go favour small interfaces? Give examples of composition.
- Q97What's wrong with this
String()method? When doesfmtcallString()orError()?