Explain gofmt/goimports and why Go enforces a single formatting style.
Quick Answer
gofmt automatically reformats Go source code into one canonical style — consistent indentation (tabs), spacing, and alignment — with no configuration options, unlike most language formatters that support dozens of style knobs. goimports does everything gofmt does, plus automatically adding missing imports and removing unused ones based on what identifiers your code actually references. Go enforces a single, non-negotiable style deliberately: it eliminates an entire category of pointless debate and PR review comments about formatting, and it means every Go codebase, from any team or company, looks structurally the same, making it easier to read unfamiliar code and reducing formatting-only diffs that add noise to code review.
Detailed Answer
Go's stance on formatting is unusually opinionated compared to most languages: there's exactly one accepted style, and the tooling enforces it automatically.
Running gofmt
gofmt -l . # list files that aren't formatted correctly
gofmt -w file.go # rewrite file.go in place to the canonical style
// Before
func add(a,b int)int{
return a+b
}
// After gofmt
func add(a, b int) int {
return a + b
}
goimports: gofmt plus import management
goimports -w file.go
// Before: fmt is used, but not imported; os is imported, but never used
import (
"os"
)
func main() {
fmt.Println("hi")
}
// After goimports
import (
"fmt"
)
func main() {
fmt.Println("hi")
}
goimports adds the missing "fmt" import automatically and drops the unused "os" import, saving a step most other languages' tooling doesn't automate as smoothly.
Why zero configuration is a deliberate choice
Most formatters (Prettier, Black, clang-format) support configuration files with dozens of options: tab width, brace placement, line length, and more. gofmt has essentially none of that. Every .go file, from any project, formats identically. This eliminates formatting-based bikeshedding in code review entirely, and means switching between codebases never requires relearning a different house style.
Practical integration
Most editors run gofmt/goimports automatically on save. Many teams add a CI check (gofmt -l . should output nothing) to guarantee no unformatted code merges, treating formatting as a build requirement rather than a style suggestion.