Using go fmt and go vet
In this page:
Formatting Code with go fmt
'go fmt' rewrites your source files in place to match Go's one true formatting style: consistent indentation, spacing, and brace placement. Because everyone's code ends up looking the same, code reviews can focus on logic instead of arguing over tabs versus spaces.
Note: Most editors run gofmt automatically on save once Go tooling is configured.
Example: Formatting Code with go fmt
go fmt ./...
⚠️ Run this command in your terminal.
What gofmt Actually Changes
Running gofmt on a file adjusts indentation to tabs, aligns struct fields and comments, and normalizes spacing around operators, without altering what the program does. It's purely cosmetic but mandatory by community convention -- almost all published Go code is gofmt-clean.
Example: What gofmt Actually Changes
package main
import "fmt"
func main() {
fmt.Println("gofmt normalizes spacing, indentation, and alignment")
}
Login to try C/C++/Java/PHP code in the editor
Catching Bugs with go vet
'go vet' examines your code for constructs that compile fine but are probably bugs, like a fmt.Printf call whose format string doesn't match its arguments, or a struct tag with invalid syntax. It's a lightweight static analysis pass that catches mistakes before they reach production.
Note: 'go vet' is often run automatically as part of 'go test'.
Example: Catching Bugs with go vet
go vet ./...
⚠️ Run this command in your terminal.
A vet-Catchable Mistake
A classic example vet flags is passing the wrong number or type of arguments to a Printf-style function -- the code compiles because Printf accepts any arguments, but the output would be wrong at runtime. Running vet regularly catches this class of error immediately.
Example: A vet-Catchable Mistake
package main
import "fmt"
func main() {
name := "Gopher"
age := 5
fmt.Printf("%s is %d years old\n", name, age)
}
Login to try C/C++/Java/PHP code in the editor
- Manually aligning spacing/tabs to match team style instead of just running 'go fmt', which makes it a non-issue.
- Ignoring 'go vet' warnings about suspicious constructs (like a Printf with mismatched format verbs) because the code still compiles.
- Committing unformatted code to version control, causing noisy diffs when someone else later runs gofmt on the same file.
- 'go fmt' automatically rewrites source files to Go's standard formatting style.
- Consistent formatting removes an entire category of code-review debate about style.
- 'go vet' analyzes code for likely bugs that still compile, such as wrong Printf verbs or unreachable code.
- Both tools are built into the standard Go toolchain -- no extra installation required.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: