Thellimist
Thellimist

Reputation: 4017

golang what is import side effect

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?

Upvotes: 24

Views: 10312

Answers (1)

evanmcdonnal
evanmcdonnal

Reputation: 48114

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.

Upvotes: 32

Related Questions