What is the point of using _ in import in go

huangapple go评论72阅读模式
英文:

What is the point of using _ in import in go

问题

在Go语言中,我看到了一种奇怪的语法用于导入包:import _ fmt

我知道import f fmt可以将该包起一个别名,而且我也知道_被用作一个不需要关心的变量。

所以毫无疑问,这里我是在导入一个我不打算使用的包。实际上,看起来就是这样。


我不明白的是为什么这样做可能有帮助。如果我使用for _, v := range(arr){},我使用_是因为我别无选择,我需要告诉编译器不用担心我不会使用的变量。

但是如果我不打算使用一个包,我会直接省略它(如果以后可能有用,我会注释掉)。没有理由将其编译并添加到源代码中。

所以,使用这种语法有什么意义,还是说这只是将别名和未使用变量结合在一起的无用产物?

英文:

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?

答案1

得分: 6

这意味着你想要导入它以产生副作用。通常与包含init的包一起使用。当然,你也可以正常导入它,但是使用_可以清楚地表明你只想要副作用。

Effective Go中搜索“Import for side effect”以获取讨论。

一个非常常见的例子是net/http/pprof,它会向默认的mux添加一些新的处理程序。像github.com/SlyMarbo/spdy这样的包也以相同的方式使用它来静默修改默认的http客户端。

英文:

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.

huangapple
  • 本文由 发表于 2015年6月4日 08:44:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/30633188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定