LinuxCommandLibrary

gofmt

Format Go source code

TLDR

Format a file and display the result to the console

$ gofmt [source.go]
copy

Format a file, overwriting the original file in-place
$ gofmt -w [source.go]
copy

Format a file, and then simplify the code, overwriting the original file
$ gofmt -s -w [source.go]
copy

Print all (including spurious) errors
$ gofmt -e [source.go]
copy

SYNOPSIS

gofmt [-d] [-e] [-l] [-r 'old -> new'] [-s] [-w] [path ...]

PARAMETERS

-d
    display diffs instead of rewriting files

-e
    report all errors (not just first 10 per line)

-l
    list files whose formatting differs from gofmt’s

-r 'old -> new'
    apply rewrite rule (e.g., 'a[b:len(a)] -> a[b:]')

-s
    simplify code by applying canonical rewrites

-w
    write result to source file instead of stdout

DESCRIPTION

gofmt is the canonical tool for formatting Go programming language source code. It enforces a standard style guide, ensuring consistent indentation (using tabs or spaces), spacing around operators, alignment of structs and interfaces, and proper line breaks. This eliminates debates over code style, allowing developers to focus on logic.

By default, gofmt reads from stdin and writes formatted code to stdout. It can process files or directories recursively when paths are provided. Key features include listing unformatted files (-l), overwriting source files (-w), displaying diffs (-d), simplifying expressions (-s), and applying custom rewrite rules (-r).

It's commonly used via go fmt ./..., which runs gofmt -l -w -s on packages. Integrated into editors like VS Code and Vim via plugins, gofmt runs on save for automatic formatting. All Go code in the standard library and official projects is gofmt-ed.

CAVEATS

gofmt is opinionated and may change code layout unexpectedly; always review diffs with -d. Does not handle //go:build lines perfectly in complex cases. Use go fmt for package-level formatting.

EXAMPLES

gofmt -l -s .
Lists and simplifies unformatted files.
gofmt -w main.go
Formats and overwrites main.go.
go fmt ./...
Formats entire package tree.

HISTORY

Developed by Rob Pike as part of Go's 2009 preview; stabilized in Go 1.0 (2012). Emphasizes 'gofmt yourself' philosophy to end style wars. Evolved with Go releases, adding -s simplification in Go 1.1.

SEE ALSO

go(1), goimports(1)

Copied to clipboard