Accidental removal of side-effect imports

Go has 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 side-effects introduced by the package).

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.

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"

If you’re importing the same package for normal use, import it twice. This way, the _ side-effect import sticks around even if the regular import is removed.

import (
    "expvar"
    _ "expvar"
)

As an added measure add a reference to the side-effect package’s symbol in your source file:

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

If the expvar import is accidentally removed, this line would fail to compile, making you consciously aware that you’ve lost the expvar import.

 
2
Kudos
 
2
Kudos

Now read this

Hibernate in Fedora

I spent time yesterday making HybridSleep and Hibernate work in Fedora 32 on a ThinkPad X1 Carbon with an encrypted disk. I don’t ever plan to manually use hybrid-sleep or hibernate; I’d instead just lock my screen or close the laptop... Continue →