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 looks like it calls 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
system change frequently. It serves as a shield or defense for cases where you forget to match the methods of atype
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 is being created by
http.Handler
assigning a new instance to it and then discarding it (which is what underscore means in Go, as infor _, elt := range myRange { ...}
if you don't care about the index of the enum).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.