LinuxCommandLibrary

go-fmt

Format Go source code automatically

TLDR

Format Go source files in the current directory

$ go fmt
copy

Format a specific Go package in your import path ($GOPATH/src)
$ go fmt [path/to/package]
copy

Format the package in the current directory and all subdirectories (note the ...)
$ go fmt [./...]
copy

Print what format commands would've been run, without modifying anything
$ go fmt -n
copy

Print which format commands are run as they are run
$ go fmt -x
copy

SYNOPSIS

go fmt [-n] [-x] [-diff] [packages]

PARAMETERS

-diff
    Display diffs between original and fixed source instead of rewriting files

-l
    List files whose formatting differs from gofmt’s required style (passed to underlying gofmt)

-n
    Print commands that would be executed, but do not run them

-r a,b
    Apply rewrite rule to replace a with b (passed to gofmt)

-s
    Simplify code by removing unnecessary parens (passed to gofmt)

-w
    Write result to source file instead of stdout (default behavior)

-x
    Print commands as they are executed

DESCRIPTION

The go fmt command is a key tool in the Go programming language toolchain, designed to automatically format Go source code according to the official Go style conventions. It ensures consistent code formatting across projects, eliminating debates over trivial style issues like indentation, spacing, and line breaks.

Invoked as go fmt followed by package paths (e.g., go fmt ./... to format the current module recursively), it runs the underlying gofmt tool with flags -l -w by default. This lists files needing changes and rewrites them in place. The command processes each package independently, reading from source files and writing formatted versions back.

Key benefits include improved readability, easier code reviews, and enforcement of Go's philosophy of simplicity. It handles complex structures like imports, composites, and function declarations precisely. Developers typically run it before commits via hooks or IDE integrations. While opinionated, Go's style is widely accepted, promoting uniformity in the ecosystem.

For large codebases, combine with go list for targeted formatting. Note that it does not fix logical errors, only stylistic ones.

CAVEATS

Modifies files in place by default; use -n or -diff to preview changes. Does not handle non-Go files or fix semantic issues. Requires Go toolchain installed.

DEFAULT BEHAVIOR

Runs gofmt -l -w on listed packages; prints paths of reformatted files to stdout.

COMMON USAGE

go fmt ./... formats entire module; integrate with git hooks for pre-commit checks.

HISTORY

Introduced in Go 1.0 (2012) as a wrapper for gofmt, which originated in early Go prototypes (2009). Evolved with Go releases; flags stabilized by Go 1.2. Promotes 'one true format' philosophy, inspired by Plan 9 tools.

SEE ALSO

gofmt(1), go(1), go list(1)

Copied to clipboard