Search⌘ K
AI Features

Imports

Explore the role of imports in Go programming, including how unused imports prevent compilation and how tools like goimports help manage them. Understand underscore imports for side effects and dot imports used mainly in testing to handle package dependencies, enabling clearer and more efficient Go code management.

Unused imports

Go programs with unused imports don’t compile. This is a deliberate feature of the language since importing packages slows down the compiler. In large programs, unused imports could make a significant impact on compilation time.

To keep the compiler happy during development, you can reference the package in some way:

Go (1.16.5)
package main
import (
"fmt"
"math"
)
// Reference unused package
var _ = math.Round
func main() {
fmt.Println("Hello")
}

goimports

A better solution is to use the goimports tool. goimports removes unreferenced imports. What’s even better is that the following widget does not use goimports and the compilation fails

Go (1.16.5)
package main
import "math" // imported and not used: "math"
func main() {
fmt.Println("Hello") // undefined: fmt
}

After running goimports: ...