Import side effects

风格不统一 提交于 2019-12-13 08:18:05

问题


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?

eg:

import _ "github.com/go-sql-driver/mysql"

db, err := sql.Open("mysql", "user:password@/dbname")

Here the import has "_" because Open statement is dependent on driver name?


回答1:


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.

This is documented in the Go spec section on package initialization.



来源:https://stackoverflow.com/questions/48427872/import-side-effects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!