导入副作用 [英] Import side effects
问题描述
我是Go和功能范式的新手.在golang中使用数据库连接时,我必须import
mysql驱动程序.我碰到了"_",它是指变量的空白标识符和导入包,它们的副作用非常大.
I am new to Go and functional paradigm. while working with database connections in golang I have to import
mysql driver. And I came across "_" which is to mention blank identifier for variables and import packages which are soley for their side effects.
搜索了副作用,并发现了
Searched for side-effects and found this side effects in es6
我不明白函数的副作用取决于全局变量,该变量偏离了纯函数的引用透明性.但是包装如何带来副作用呢? 是因为对软件包的依赖产生了副作用吗?
What I didn't understand is side effect of a function is dependent on a global variable which deviates the referential transparency of a pure function. But how does a package can bring side effect? Is it because the dependency on the package as side effect?
例如:
import _ "github.com/go-sql-driver/mysql"
db, err := sql.Open("mysql", "user:password@/dbname")
由于Open
语句取决于驱动程序名称,因此导入中包含"_"吗?
Here the import has "_" because Open
statement is dependent on driver name?
推荐答案
对_
导入感兴趣的主要副作用是init
函数的执行.程序包可以包含init
函数,该函数将在程序启动时在执行main
之前执行.对于DB驱动程序,它用于注册驱动程序,因此您可以将其与sql.Open
一起使用. expvar
和pprof
软件包都在其init
函数中注册了HTTP处理程序,并且类似地经常与_
导入一起使用.
The main side-effect one is interested in with an _
import is the execution of init
functions. A package can include an init
function which will be executed when the program starts, before main
is executed. In the case of DB drivers, this is used to register the driver so you can use it with sql.Open
; expvar
and pprof
packages both register HTTP handlers in their init
functions, and are similarly often used with _
imports.
关于包初始化的规范部分中对此进行了记录.
这篇关于导入副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!