LinuxCommandLibrary

goimports

Automatically update Go import lines

TLDR

Display the completed import source file

$ goimports [path/to/file.go]
copy

Write the result back to the source file instead of stdout
$ goimports -w [path/to/file.go]
copy

Display diffs and write the result back to the source file
$ goimports -w -d [path/to/file.go]
copy

Set the import prefix string after 3rd-party packages (comma-separated list)
$ goimports -local [path/to/package1,path/to/package2,...] [path/to/file.go]
copy

SYNOPSIS

goimports [-d] [-e] [-format={goimports|gofmt}] [-ignore=path1,path2] [-l] [-local=prefix1,prefix2] [-srcdir=dir] [-v] [-w] [path ...]

PARAMETERS

-d
    display diffs of changes instead of rewriting files

-e
    add explanatory comments to excluded imports

-format=goimports|gofmt
    choose formatting tool for output (default: goimports)

-ignore=path,path
    comma-separated list of import paths to ignore

-l
    list files whose imports differ from goimports's without rewriting

-local=prefix,prefix
    comma-separated prefixes for local packages (after 3rd-party)

-srcdir=dir
    use dir for import path resolution

-v
    enable verbose logging

-w
    write changes to files instead of stdout (default: false)

DESCRIPTION

goimports is a command-line tool in the Go ecosystem that automatically manages import statements in Go source code files. It identifies and removes unused imports, adds missing imports required by the code, and organizes them into a standard format: first the standard library packages, then third-party packages alphabetically, followed by local packages.

The tool analyzes the actual usage of imports in the code, making it smarter than simple linters. It supports both GOPATH and Go modules workflows, resolving import paths correctly based on the source directory or module context.

Commonly used in editors like Vim, VS Code, or Emacs via plugins, or in build pipelines with go fmt equivalents. Running goimports -w file.go rewrites the file in place, while -l lists files needing changes without modifying them. It's essential for maintaining clean, idiomatic Go codebases and enforcing consistent import styles across teams.

CAVEATS

Requires Go installed and proper GOPATH/module setup for accurate import resolution; ignores non-Go files; may require -srcdir for vendored code.

COMMON USAGE

goimports -w . formats all Go files in current directory.
goimports -l . lists files needing import fixes.

EDITOR INTEGRATION

Use via LSP servers or plugins in VS Code, Vim (ale/gopls), Emacs; often aliased with gofmt.

HISTORY

Developed by the Go team as part of golang.org/x/tools/cmd/goimports around Go 1.1 (2012); evolved with Go modules in 1.11; actively maintained for modern Go workflows.

SEE ALSO

gofmt(1), go(1), golint(1)

Copied to clipboard