Published on

The Underscore Character in Go Imports


In Go like many languages the _ is used to indicate that something should not be used. For example if you have a function that returns multiple return values you actually have to name the items you are not interested in using underscores otherwise you will get compile errors for unused variables:

result, _ := functionThatDoesSomething()

One thing I saw today which tripped me up a bit was using a named import with an underscore for a DB driver:

import (
  _ "domain/db/driver"

My understanding of the use of _ tripped me up here as why would you import something but essentially ignore it and not be able to use it (as soon as you underscore it you can no longer refer to its members using the package name)? Go should also not be able to compile this if there is an unused import. It turns out you import like this if the package is a work in progress or if you want to import something for the initialization side effects it brings. In my case for a DB driver this second reason makes the most sense.