gofmt
gofmt is the standard formatter for Go source. It decides indentation, spacing, and import grouping. The compiler does not run it, but every Go project expects its output.
Detailed Explanation
Go has one formatting argument, and gofmt won it. You do not configure tab width, brace style, or whether a comma dangles. The tool reads a file and writes a canonical form. gofmt -w . writes in place. go fmt is a thin wrapper that runs gofmt on packages. Editors run it on save. Code review tools fail the build if the diff is not gofmt-clean.
What it changes. Tabs for indentation. Alignment of consecutive declarations and struct tags when it improves scanability. Import blocks sorted and grouped: standard library, then a blank line, then the rest. It does not sort your logic, rename variables, or fix compile errors. A file that does not parse is left alone and gofmt exits non-zero.
goimports and gofumpt. goimports is gofmt plus adding and removing import lines from your module cache and std. Most editors use it instead of raw gofmt. gofumpt is a stricter fork (empty lines, literal style). Teams that adopt it must run it everywhere; mixing gofmt and gofumpt produces noisy diffs. The language's contract is gofmt. Extra tools are a team choice.
Why the opening brace is on the same line. gofmt will not move a brace to the next line, and the compiler inserts semicolons at newline, so if cond\n{ is a syntax error. The formatter and the grammar agree. You cannot "fix it in settings."
What it costs. Zero runtime. A few milliseconds per file on save. The social cost is the one-time habit of not fighting the tool. The benefit is that review comments about alignment disappear, and git blame is not littered with "fix tabs" commits. Run gofmt -w on a whole repo once when you adopt it, in its own commit.
Code Examples
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 1 {
fmt.Println(os.Args[1])
}
}# Format every Go file under this directory, in place.
gofmt -w .
# Check without writing (useful in CI): non-empty output means dirty files.
gofmt -l .gofmt groups and sorts imports. Do not hand-align them.
// gofmt groups and sorts imports. Do not hand-align them.
import (
"fmt"
"example.com/shop/internal/httpapi"
)Common Gotchas
`gofmt` does not compile the file
a formatted file can still fail `go test`. Formatting is not type-checking.
Generated files should still be gofmt-clean
generators that emit odd spacing create permanent diffs. Run `gofmt` in the generator or after `go generate`.
Alignment of struct tags can change when you add a longer field
a one-field rename may reflow a whole block. That is expected; do not disable alignment.
`gofmt -r` can apply simple rewrites
it is a rare tool, not a refactoring engine. Prefer `gofmt -w` for everyday use.