0

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?

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753

1 Answers1

6

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.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Can you please explain what side effects can I get (apart of boosting the size of an execution file) – Salvador Dali Jun 04 '15 at 00:46
  • Usually, the side effect is something gets registered with some other library. For example, most SQL database drivers, import for side effect and then you can use sql.Open("dbname","url") – David Budworth Jun 04 '15 at 01:21