We’re continuing today our discussion of imports. Yesterday we left off with using explicit package names in an import clause when the package name differs from the last element of the import path.
Is that the only reason to explicitly name your imports? No. Sometimes you need to disambiguate between two imports with the same package name. Or maybe you just like a shorter name.
import (
log "github.com/sirupsen/logrus" // Shorter names are nice
stdlog "log" // Oh, but we need to reference this package, too
)
There is one exception to the rule “Name your packages the same as the last element of your import path,” though: v2+ releases.
import (
"math/rand/v2"
)
When you release a Go module with a major version of 2 or greater, that version is appended as the last element of the import path, but in this case, convention is to use the second-to-last path element as the name. In the above example, the package is called math
. This leads to another rule: Don’t ever name your packages vX
where X is an integer. It will confuse everyone! Fortunately, I’ve only run into this once in the real world.
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)