This question already has an answer here:
I have seen a strange syntax in go while importing packages: import _ fmt
.
I am aware that import f fmt
works like an alias for this package and also I know that _
is used as a variable that should not be cared about.
So no prize for guessing that here I am importing a package that I am not going to use. And in fact it looks like this is what happening here.
What I fail to understand is why this might be helpful. If I use for _, v := range(arr){}
I use _
because I have no choice and I need to specify to the compiler that it should not worry about the variable that I will not be using.
But if I do not intend to use a package, I would just omit it (if it might be useful later, I would comment it). But no reason for it to be compiled and added to source code.
So is there any point of using this syntax, or is this just a useless artifact from combining aliasing and unused variables?
</div>
It means that you want to import it for the side effects. It's usually used with packages that include an init
. Of course you could import it normally, too, but the _
makes it clear that you only wanted the side effects.
Search for "Import for side effect" in Effective Go for discussion.
A very common example is net/http/pprof
, which attaches some new handlers to the default mux. Packages like github.com/SlyMarbo/spdy
use it in the same way to silently modify the default http client.