How to Use go vet: Syntax, Example, and Common Pitfalls
Use
go vet by running it in your terminal inside your Go project directory to analyze your code for common mistakes and suspicious constructs. It checks your code without compiling it fully and reports issues to help you write better Go programs.Syntax
The basic syntax of go vet is simple. You run it in your terminal followed by optional flags and the package or files you want to check.
go vet [flags] [packages]flagsmodify the behavior (usually none needed for basic use)packagesspecify which Go packages or files to analyze (default is current directory)
Example: go vet ./... checks all packages in the current module recursively.
bash
go vet [flags] [packages] # Example: go vet ./...
Example
This example shows how go vet detects a suspicious printf call with mismatched arguments.
go
package main import "fmt" func main() { name := "Alice" age := 30 // Incorrect: missing argument for age fmt.Printf("Name: %s, Age: %d\n", name) }
Output
# command-line-arguments
./main.go:9:39: Printf format %d has arg missing
Common Pitfalls
Common mistakes when using go vet include:
- Ignoring its output, which can catch subtle bugs early.
- Running it outside your project directory, so it finds no files.
- Confusing
go vetwithgo buildorgo test;go vetonly checks code correctness, not compilation or tests.
Always fix reported issues to improve code quality.
go
package main import "fmt" func main() { var x int // Wrong: unused variable x triggers vet warning fmt.Println("Hello") }
Output
# command-line-arguments
./main.go:6:6: x declared and not used
Quick Reference
| Command | Description |
|---|---|
| go vet | Run vet on current package |
| go vet ./... | Run vet on all packages recursively |
| go vet -all | Enable all checks (default) |
| go vet -printfuncs=func1,func2 | Add custom printf-like functions to check |
| go vet -shadow | Detect variable shadowing issues |
Key Takeaways
Run
go vet in your project directory to find common Go code mistakes.go vet helps catch bugs like format string errors and unused variables before compiling.Use
go vet ./... to check all packages recursively.Pay attention to
go vet warnings and fix them to improve code quality.Remember
go vet checks code correctness, not compilation or tests.