golang导入有什么副作用 [英] golang what is import side effect

查看:41
本文介绍了golang导入有什么副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

有效行事中说,这种进口意味着副作用.我已经阅读了几个SO答案,但是都没有解释什么是 import副作用.有人可以详细说明导入副作用吗?

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?

推荐答案

当他们说导入副作用"时,他们实际上是指静态使用的代码/功能.意味着仅导入软件包会导致一些代码在应用程序启动时执行,从而使我的系统处于与未导入该软件包的状态不同的状态(例如 init()中的代码例如注册处理程序,它也可以放下配置文件,修改磁盘上的资源,等等.有效的go教程只是为了解释这一点,以说明开发人员可能要进行空白导入的原因. import _"somepackageImNotUsingReally"

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"

当我说的是 init()时,添加了其他上下文; https://golang.org/doc/effective_go.html#init -任何导入的软件包将在调用main之前先调用其init方法. init()中的任何内容都是副作用.我认为不可能有其他任何东西,因为常量之类的东西将在包范围内,而不是在全局范围内,因此它不会重新定义常量或类似的东西.

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.

如注释中所指出并在上面的init链接中所述,在包中的所有变量声明都对其初始化程序求值后,才调用",这意味着 PackageScopeVar:= unexportedInitializerThatWritesToDisc()这样的代码将被调用会产生副作用.

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.

这篇关于golang导入有什么副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆