How to Use go vet for Static Analysis

Run `go vet` on your package to detect suspicious constructs like unreachable code, incorrect format strings, and shadowed variables that the compiler misses.

Run go vet on your package to detect suspicious constructs like unreachable code, incorrect format strings, and shadowed variables that the compiler misses. It acts as a fast, built-in static analyzer that integrates directly into your build workflow without needing external dependencies.

To check a specific package in your current directory, simply run:

go vet ./...

This recursively analyzes all packages in the current module. If you want to enforce stricter checks, such as detecting unused variables or potential nil pointer dereferences, you can enable specific vet checks via flags. For example, to ensure all variables are used and to check for common logic errors:

go vet -printfuncs="log.Printf,log.Errorf" ./cmd/myapp

The -printfuncs flag tells go vet to treat custom logging functions as printf-style functions, allowing it to validate format strings against arguments.

You can also integrate go vet into your CI/CD pipeline or pre-commit hooks to fail builds on violations. A common pattern is to run it alongside go build to catch issues early:

go vet ./... && go build ./...

If go vet finds issues, it outputs them to stderr and returns a non-zero exit code, which is perfect for automation. Note that go vet is not a linter like golangci-lint; it focuses on a specific set of high-confidence, low-maintenance checks defined in the standard library. For more comprehensive style and complexity analysis, you would typically combine go vet with golangci-lint, but go vet remains the essential first line of defense for correctness.

If you need to suppress a specific warning for a legitimate case, you can use a comment directive on the line above the code:

//go:vetignore
var unusedVar int

However, prefer fixing the underlying issue over suppressing warnings. The tool is designed to be opinionated about Go idioms, so most warnings indicate actual bugs or anti-patterns. Running it frequently during development prevents these issues from accumulating and becoming harder to fix later.