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
?
Importing simply means bringing the specified package from its source location to the destination code, wiz the main program. Import in Go is very important because it helps bring the packages which are super essential to run programs.
Short answer: It's for importing a package solely for its side-effects. From the Go Specification: To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name: import _ "lib/math"
To import a package, we use import syntax followed by the package name. 💡 Unlike other programming languages, a package name can also be a subpath like some-dir/greet and Go will automatically resolve the path to the greet package for us as you will see in the nested package topic ahead.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With