What the dot, alias, and underscore mean in Go imports
Created|Updated
|Post View:
I used to look at a Go import and wonder why some packages had a name in front of them, some had a dot, and some had an underscore. It helps to separate two questions: where does Go find the package, and how do I refer to it in this file?
Where the package lives
1 2 3 4
import ( "./mypackage"// relative path "github/myrepo/mypackage"// full import path )
Of the two styles in my notes, I prefer the full import path. If I move the importing file, a relative path that used to point to the right directory can suddenly mean something else.
When you want to call Println without the prefix
1 2 3
import( . "fmt" )
If you come from Python, think from fmt import *. With an ordinary Go import, the package name is right there at the call site:
1 2 3 4 5 6 7
import ( "fmt" )
funcmain() { fmt.Println("Hello world") }
The dot puts the exported names in scope for this file, so the call gets shorter:
1 2 3 4 5 6 7
import ( . "fmt" )
funcmain(){ Println("Hello world") }
When you want a different prefix
1 2 3
import ( f "fmt" )
This works much like Python’s import numpy as np. The package still has its own name at the call site; I just get to pick what that name is.
1 2 3 4 5 6 7
import ( f "fmt" )
funcmain(){ f.Println("Hello world") }
When you only want the package to initialize
1 2 3
import ( _ "github.com/myrepo/package" )
Sometimes I don’t need to call anything in the package at all. The blank identifier lets me import it so its initialization code runs, including any init functions.