Golang中的”import side effect”是什么意思?

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

golang what is import side effect

问题

以下是要翻译的内容:

import (
    _ "github.com/lib/pq"
    _ "image/png"
    ...
)

在《Effective Go》中提到这种类型的导入意味着副作用。我已经阅读了几个 Stack Overflow 的答案,但没有一个解释了什么是“导入副作用”。有人可以详细解释一下“导入副作用”这个术语吗?

英文:
import (
    _ "github.com/lib/pq"
    _ "image/png"
    ...
)

In effective go it says that these kinds of imports mean side effect. I've read several SO answers but none explain what is an import side effect. Could someone elaborate the term import side effect?

答案1

得分: 25

当他们说“导入副作用”时,实际上是指在静态使用的代码/功能。这意味着仅仅导入包将导致一些代码在应用程序启动时执行,使我的系统处于与未导入该包时不同的状态(例如,在他们的示例中注册处理程序的代码,还可以放置配置文件,修改磁盘上的资源等)。《Effective Go》教程简单地解释了这一点,以说明开发人员可能希望进行空白导入的原因,例如import _ "somepackageImNotUsingReally"

编辑:为了增加额外的上下文,当我说init()时,我指的是这个方法;https://golang.org/doc/effective_go.html#init - 在调用main之前,所有导入的包都会调用它们的init方法。init()中的任何内容都是副作用。我不认为还有其他副作用,因为像常量这样的东西将位于包范围而不是全局范围,所以它不会重新定义常量或类似的东西。

编辑2:正如评论中指出并在上述init链接中解释的那样,“在包中的所有变量声明评估其初始化程序之后调用”意味着像PackageScopeVar := unexportedInitializerThatWritesToDisc()这样的代码将运行并可能具有副作用。

英文:

When they say 'import side effects' they are essentially referring to code/features that are used statically. Meaning just the import of the package will cause some code to execute on app start putting my system in a state different than it would be without having imported that package (like code in an init() which in their example registers handlers, it could also lay down config files, modify resource on disc, ect). The effective go tutorial is explaining this simply to illustrate reasons why a developer might want to do a blank import ie; import _ "somepackageImNotUsingReally"

EDIT: to add additional context when I said init() I was referring to this method; https://golang.org/doc/effective_go.html#init - any imported packages will have their init methods called prior to main being called. Whatever is in the init() is a side effect. I don't think there can be any others because things like constants will be at the package scope, not the global scope so it wouldn't redefine constants or anything like that.

EDIT2: as pointed out in comments and explained in the init link above " is called after all the variable declarations in the package have evaluated their initializers" meaning code like PackageScopeVar := unexportedInitializerThatWritesToDisc() will run and could have side effects.

huangapple
  • 本文由 发表于 2015年9月9日 03:09:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/32465453.html
匿名

发表评论

匿名网友

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

确定