liveBook · Manning

Goimports

As explained in Go in Practice, Second Edition

goimports is a Go formatting tool that formats source code and adds or removes package imports based on usage.

goimports formats Go source code and keeps its import list in step with package usage. It wraps gofmt, adds missing imports, and removes unused ones that could cause compiler errors after a refactor. For routine formatting, it can take the place of go fmt. section 6.1.1 section 1.2.4

To make it part of a workflow:

  • Install it with `go install golang.org/x/tools/cmd/goimports@latest`, then run `goimports [FILE_PATTERN].go` on the files you want to format. section 6.1.1
  • In GoLand, add goimports as a File Watcher for saved `.go` files. In VS Code, enable Format on Save. section 6.1.1

After editing imports

Suppose a Go file still imports a package removed during a refactor, or uses a package without importing it. Run goimports to remove the unused import or add the missing one while formatting the file. section 6.1.1

How Go in Practice, Second Edition covers it

How deep it goes
Gives installation, command syntax, and editor setup; does not explain how imports are detected internally.
Examples
Uses a badly formatted Go file and save-time formatting in GoLand and VS Code as workflow examples.
What it assumes
Assumes familiarity with Go files and package imports while supplying the installation and invocation commands.
What you can do after
Apply it via goimports to format Go files and correct missing or unused imports.
How it connects
Connects gofmt, go fmt, package imports, compiler errors, and editor format-on-save workflows.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.