问题
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