Skip to content
Tutorials Center
My learning

Topics

Lesson 103 of 147 ยท Testing and Tooling

go vet, gofmt and Linting

Catch Go bugs before they run - what go vet reports, how gofmt and goimports format code, what staticcheck and golangci-lint add, plus a CI setup you can copy and a mini linter built on go/ast.

The Go compiler already refuses a lot: unused variables, unused imports, mismatched types, missing returns. But a program can compile and still be wrong in ways that a machine can see without running it. Printing an int with %s, copying a mutex, ignoring the cancel function of a context, a condition that can never be true. Go's tooling has three layers for this. gofmt settles how code looks. go vet finds suspicious code that the compiler accepts. Linters such as staticcheck and golangci-lint go further and enforce style and catch subtler mistakes.

This lesson shows what each tool does, what its messages look like, how to run them in your editor and in CI, and (to remove the magic) how a linter works inside by building a tiny one with the go/parser and go/ast packages. You met the commands briefly in the tooling basics lesson; here we go deeper. Because these tools are programs that read your source files, the commands and their output are shown read-only, and everything that can run on this site does.

gofmt: one style for everyone

Go has exactly one accepted layout, and a tool applies it: gofmt. It uses tabs for indentation, puts spaces around binary operators in a consistent way, aligns struct fields and comments, orders imports alphabetically within a block, and normalizes blank lines. Nobody argues about brace placement or tabs versus spaces, because there is nothing to argue about. Code reviews stay about the logic.

Typical commands:

Terminal
gofmt -l .          # list files whose formatting differs (prints nothing if all is well)
gofmt -d main.go    # show the differences as a diff
gofmt -w .          # rewrite the files in place
gofmt -s -w .       # also apply safe simplifications
go fmt ./...        # runs gofmt -l -w on the packages (what most people type)

The -s flag rewrites code into a simpler equivalent form, for example x[1:len(x)] to x[1:], for _ = range x to for range x, and []Point{Point{1, 2}} to []Point{{1, 2}}.

gofmt is also a library. The go/format package exposes the same formatter, which is how editors, code generators and this page can use it. The program below takes deliberately messy source text and formats it:

Go Formatting source with go/format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Look at what changed: the imports are sorted (fmt before os), the body of every function is indented with a tab, operators got their spaces, and the closing brace of the for loop moved to its own line. gofmt works on the syntax tree, not on text, so it never changes what the program means. It also refuses to format code that doesn't parse and reports the position of the syntax error.

Set your editor to format on save (the Go extension for VS Code and GoLand do this by default through gopls). Then you never run gofmt by hand, and a CI check that gofmt -l . prints nothing can't fail for style reasons.

goimports and gofumpt

goimports is gofmt plus import management: it adds missing imports (when you type strings.ToUpper, it adds "strings"), removes unused ones, and groups standard-library imports separately from third-party ones. Editors usually run it for you through gopls. The -local flag puts your own module's packages in a third group.

Terminal
go install golang.org/x/tools/cmd/goimports@latest
goimports -w -local example.com/myapp .

gofumpt is a stricter superset of gofmt (no empty line at the start of a block, 0o644 instead of 0644, grouped var declarations, and similar). It is optional. Use it only if the whole team agrees, because it will reformat code that plain gofmt accepts.

go vet: bugs the compiler accepts

go vet runs a set of analyzers, each looking for one kind of suspicious construct. It reports code that is legal but almost certainly not what you meant. Run it on the whole module:

Terminal
go vet ./...

A few facts about it:

  • It needs the code to compile; type errors come first.
  • It aims for high precision: when vet speaks, you should listen. It deliberately skips checks that would produce many false alarms.
  • go test runs a small, high-confidence subset of the analyzers automatically before the tests, so the worst mistakes fail your build even if you forget to run vet.
  • You can run or skip single analyzers: go vet -printf ./..., or go vet -copylocks=false ./.... The list of analyzers is shown by go tool vet help.

Here are the checks you will meet most often. In each case the code compiles, and go vet complains. The messages below show the usual shape of vet's output; the wording can change slightly between Go versions.

printf: verbs that don't match their arguments

Go
package main

import "fmt"

func main() {
	name := "Ada"
	fmt.Printf("%d items for %s\n", name, 3)
	fmt.Printf("%s and %s\n", name)
	fmt.Println("total: %d", 5)
}
TEXT
$ go vet ./...
# example.com/app
./main.go:7:2: fmt.Printf format %d has arg name of wrong type string
./main.go:7:2: fmt.Printf format %s has arg 3 of wrong type untyped int
./main.go:8:2: fmt.Printf format %s reads arg #2, but call has 1 arg
./main.go:9:2: fmt.Println call has possible Printf formatting directive %d

The check knows fmt and every function in your code that forwards to it (a wrapper like func logf(format string, args ...any) is detected automatically). Go 1.24 added a check for fmt.Printf(s) where s is not a constant and there are no other arguments, because a % inside s would be misread as a verb; the fix is fmt.Print(s) or fmt.Printf("%s", s).

copylocks: copying a mutex

Go
type Counter struct {
	mu sync.Mutex
	n  int
}

func (c Counter) Inc() { // value receiver: every call works on a copy
	c.mu.Lock()
	defer c.mu.Unlock()
	c.n++
}
TEXT
./main.go:11:7: Inc passes lock by value: main.Counter contains sync.Mutex

A sync.Mutex must never be copied after first use, and this method both copies it and throws the increment away. The fix is a pointer receiver (func (c *Counter) Inc()); see value vs pointer receivers. The same analyzer catches range loops over slices of lock-containing structs and function arguments passed by value.

Other analyzers worth knowing

Analyzer What it reports
lostcancel The cancel function from context.WithCancel/WithTimeout is discarded or not called on every path, which leaks the context's resources
unreachable Code after return, panic or an infinite loop that can never run
unusedresult Ignoring the result of a pure function such as fmt.Sprintf or errors.New
loopclosure A closure or goroutine captures a loop variable. With Go 1.22+ semantics, each iteration has its own variable and the check stays quiet; it still fires for modules whose go.mod says an older version
structtag A malformed or duplicated struct tag such as json: "name"
bools Redundant or suspicious boolean expressions such as `x != 1
assign Self-assignment such as x = x
atomic Mistakes with sync/atomic, like x = atomic.AddInt64(&x, 1)
errorsas A second argument to errors.As that isn't a pointer
httpresponse Using resp.Body before checking the error from http.Get
slog Mismatched key-value arguments to log/slog calls
stdmethods Methods like String or Format with the wrong signature for their well-known interface
waitgroup wg.Add called inside the goroutine it is meant to count (added in Go 1.25)
tests Malformed test, benchmark, fuzz and example names
timeformat Date layouts that use 2006-02-01 (day and month swapped) instead of 2006-01-02

The bugs, as they behave at runtime

It helps to see that these are not style problems. Each line below is something vet would flag, run here to show what actually happens:

Go What the vet warnings protect you from

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

None of these lines produced a compile error, and none crashed. They quietly produced wrong output: %!d(string=three), %!s(MISSING), %!(EXTRA int=2), a counter stuck at 0, and a JSON key named Name instead of name. That is exactly why vet exists: these mistakes are found by looking at the code, and they are much cheaper to catch before the program runs. (The %!verb(...) forms are explained in printing with fmt.)

More silent mistakes

Three more analyzers catch mistakes of the same kind. Again, each line compiles and runs without complaint:

Go timeformat, bools and unusedresult

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The swapped date prints 2030-04-03 for March 4, which would be a nasty bug in a log file or a file name; classify(404) returns unexpected even though 404 is the code the function was written for; and strings.TrimSpace(s) on its own line does nothing at all. The timeformat, bools and unusedresult analyzers report all three.

Fixing and silencing

Fix the code. If you are sure that a vet warning is a false positive, restructure the code so that the warning disappears, because vet has no inline suppression comment. Linters such as golangci-lint do offer //nolint comments (see below), which is one of the reasons teams add them.

How a linter works: build a tiny one

Every Go linter does the same three things: parse the source into a syntax tree (go/parser), walk the tree (go/ast), and report positions (go/token). Real analyzers also use type information from go/types, and they plug into the shared golang.org/x/tools/go/analysis framework, which go vet, staticcheck and gopls all use. The program below skips types and works on the tree alone. It parses a small source file held in a string and reports four kinds of problem:

Go A mini linter with go/parser and go/ast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output has the same file:line:column: message shape as any Go tool, which is what lets editors turn it into clickable errors. The walk is the same for every analyzer: ast.Inspect calls your function for each node, you switch on its type, and you look at the children. Real analyzers do the same with more care. For instance, they use type information so that fmt is recognized even if someone imports it under another name, and they offer suggested fixes that the editor can apply with one click.

staticcheck: the thorough linter

staticcheck is the most respected standalone linter for Go. Its checks have codes with a prefix that tells the category:

Prefix Category Example
SA Static analysis: real bugs SA4006: a value is assigned and never used; SA1019: use of a deprecated function
S Simplifications S1002: omit comparison with a boolean constant
ST Style ST1005: error strings should not be capitalized
QF Quick fixes Suggestions an editor can apply
U Unused code U1000: unused function or field
Terminal
go install honnef.co/go/tools/cmd/staticcheck@latest
staticcheck ./...

It finds things vet is too cautious to report, such as calling a function that the standard library has marked // Deprecated: (see comments and documentation), ineffective assignments, unused code, and misuse of time, regexp and strings functions. Its configuration lives in staticcheck.conf in your module, where you can enable or disable checks by code.

golangci-lint: many linters, one command

Running ten linters separately is slow and awkward. golangci-lint bundles dozens of them behind a single command with a shared cache, one configuration file and parallel execution:

Terminal
golangci-lint run          # lint the module
golangci-lint run --fix    # apply the fixes that linters offer
golangci-lint fmt          # run the enabled formatters (gofmt, goimports, ...)

The default set already includes govet, staticcheck, errcheck (an ignored error return), ineffassign and unused. Teams usually add a few more by writing a .golangci.yml in the repository root (this is the version 2 format):

YAML
version: "2"

linters:
  default: standard        # govet, staticcheck, errcheck, ineffassign, unused
  enable:
    - bodyclose            # HTTP response bodies must be closed
    - errorlint            # use errors.Is / errors.As and %w
    - gocritic             # many style and performance checks
    - misspell             # typos in comments and strings
    - revive               # configurable style rules (successor of golint)
    - unconvert            # unnecessary type conversions
  settings:
    errcheck:
      check-type-assertions: true
  exclusions:
    paths:
      - internal/generated

formatters:
  enable:
    - gofmt
    - goimports

Two warnings about linters in general:

  • Start small. Turning on every linter in an existing project produces thousands of findings, and nobody reads them. Enable a few that find real bugs (errcheck, staticcheck, bodyclose, errorlint), fix everything, then add more. Style linters like revive or gocritic are optional.
  • Suppress with a reason. When you disagree with a finding, add an exception on that line and explain it, so a reader knows it was deliberate:
Go
defer f.Close() //nolint:errcheck // read-only file, nothing to recover from

Linters are opinions. If a rule produces more arguments than bugs, switch it off in the configuration for the whole project instead of sprinkling comments everywhere.

Run it automatically

Tools only help if they run. Use three layers:

  1. In the editor. gopls runs vet-style analyzers as you type and formats on save. This is the fastest feedback.
  2. Before the commit (optional). A Git pre-commit hook or a tool such as lefthook runs gofmt -l and go vet ./... on the changed packages.
  3. In CI, where nobody can forget. A minimal GitHub Actions workflow (read-only; pin versions that are current when you read this):
YAML
name: ci
on:
  push:
    branches: [main]
  pull_request:

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version-file: go.mod   # use the version the module declares

      - name: Formatting
        run: test -z "$(gofmt -l .)"

      - name: Vet
        run: go vet ./...

      - name: Tests (with the race detector)
        run: go test -race -cover ./...

      - uses: golangci/golangci-lint-action@v8
        with:
          version: v2.1

The formatting step fails when gofmt -l . prints any file name: test -z succeeds only if the string is empty. go test -race also catches data races that no linter can (data races). Keep the whole pipeline fast; a check that takes ten minutes will be skipped.

Modernizing old code

Go keeps adding features that make old patterns unnecessary: for i := range 10, slices.Contains, min and max, any instead of interface{}. The tooling can upgrade your code for you. Recent Go releases rebuilt go fix on top of the same analysis framework, and it applies these "modernizer" rewrites to a package (run go fix -h to see what your version offers). Review the diff like any other change.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does gofmt -l . print when every file is already formatted?

    gofmt -l lists only the files whose formatting differs from gofmt's output, so it prints nothing when everything is formatted. That is why CI checks it with test -z.
  2. 2. This compiles, but go vet reports it. Why? fmt.Printf("%d\n", "seven")

    The printf analyzer checks verbs against argument types. At run time this call prints %!d(string=seven) instead of failing.
  3. 3. Why is func (c Counter) Inc() a problem when Counter contains a sync.Mutex?

    A value receiver works on a copy. The copylocks analyzer flags copying a lock, and the increment disappears with the copy. Use a pointer receiver.
  4. 4. Which tool bundles many linters (including staticcheck and errcheck) behind one command and one configuration file?

    golangci-lint runs many linters in parallel with a shared cache and reads a .golangci.yml file.
  5. 5. What does the json: "name" tag (with a space after the colon) do to the field when encoding JSON?

    A tag with bad syntax can't be parsed by reflect.StructTag, so encoding/json silently ignores it and uses the field name.

Summary

  • gofmt applies the one standard layout; go fmt ./..., gofmt -l . and go/format all use it. goimports also manages imports.
  • go vet ./... finds code that compiles but is almost certainly wrong: printf verb mismatches, copied locks, lost cancel functions, unreachable code, bad struct tags and more. It favors precision, and go test runs a subset automatically.
  • Linters are built on go/parser, go/ast and the analysis framework. They walk a syntax tree and report file:line:col: message.
  • staticcheck adds deeper bug checks (SA), simplifications (S) and unused code (U); golangci-lint runs many linters at once from .golangci.yml.
  • Start with a few linters, suppress findings only with a written reason, and run everything in the editor and in CI.

Next: Documentation and Examples