Accidental removal of side-effect imports

Go provides the ability to import a package purely for the package's side-effects (i.e. you don't actually use a symbol from the package in your code, but just want any side-effects introduced by the package's init function).

As an example, look at package expvar in the standard library. Importing the package registers a HTTP handler at "/debug/vars" that prints the state of published vars, as a side-effect of importing the package.

The importing source file may not even necessarily reference any symbols in package expvar. However, this means that it's easy to lose the import during refactoring or when running goimports(1) on the file.

Import with an underscore

To avoid losing the import, when you import a package for its side-effects, import it with an underscore, so that it isn't removed by goimports.

import (
	_ "expvar"
)

Import separately for each kind of use

If you're also importing the same package for normal use, import it twice—once with the underscore and once without. This way, the _ side-effect import sticks around even if the regular import is removed.

import (
	"expvar"
	_ "expvar"
)

Reference a symbol

As an additional measure, include a reference to any of the side-effect package's symbols in your source file. If the expvar import is accidentally removed, this line would fail to compile, making you consciously aware that you've accidentally lost the side-effect import.

// NOTE: this exists to guard against accidental removal of
// the expvar import, which is imported for for its
// side-effects.
var _ = expvar.Do