What does "var _ x = foo()" do in Go?


I am reading the code of a package , and I see the following:

// Make sure the Router conforms with the http.Handler interface
var _ http.Handler = New()

What does that do?

It seems to call New() , which returns the type of http.Handler , but the result is discarded… Why do that?


Translation from SO of the question what does a underscore and interface name after keyword var in golang mean?

Adapted from the answer by zzzz :

Provide static validation (at compile time) for the interface to be satisfied. The _ used as the variable name tells the compiler to effectively discard the RHS value, but to validate it to see if it has any side effects, but the anonymous variable itself does not take any process space.

This is a useful method when you are developing and the interface methods and/or the methods implemented by a type change frequently. It serves as a shield or defense for cases where you forget to match the methods of a type and an interface where the goal is to make them compatible. It helps to effectively prevent the installation of a failed (intermediate) version using such bypass.

Adapted from the answer by val :

Apparently a "dummy" value of type http.Handler is being created by allocating a new instance to it and then discarding it (which is what underscore means in Go, as in for _, elt := range myRange { ...} you are interested in the index of the enumeration).

I assume that it simply corresponds to a static validation to ensure that the interface is implemented. This way, when you change the implementation, the compiler will complain early if the interface implementation fails because it won't be able to cast the new interface.

Scroll to Top