go vet

suggest change

go vet looks at your source code for mistakes the compiler can't catch: Printf verbs that don't match their arguments, mutexes copied by value, a cancel function that's thrown away, errors.As called with a non-pointer, and many more. The code compiles and often seems to work, but it's almost certainly a bug.

This article covers:

All output below is from Go 1.27.

Running go vet

go vet takes the same package patterns as go build:

go vet            # package in the current directory
go vet ./...      # current package and all packages below it
go vet ./cmd/...  # a subtree

Here's a program that compiles and runs:

package main

import (
	"fmt"
	"os"
)

func main() {
	name, count := "cart", 3
	fmt.Printf("%s has %d items\n", count, name)
	fmt.Printf("total: %d\n")

	msg := "100% done"
	fmt.Printf(msg)

	if len(os.Args) > 5 {
		return
		fmt.Println("unreachable")
	}
}
%!s(int=3) has %!d(string=cart) items
total: %!d(MISSING)
100%!d(MISSING)one

All three lines are garbled. go vet finds every problem without running the code:

$ go vet
main.go:10:14: fmt.Printf format %s has arg count of wrong type int
main.go:11:21: fmt.Printf format %d reads arg #1, but call has 0 args
main.go:14:13: non-constant format string in call to fmt.Printf
main.go:18:3: unreachable code

Each line is file:line:column: message. Editors and CI systems understand this format, so you can click through to the code.

When it finds problems, go vet exits with status 1, so go vet ./... && go build ./... stops at the first problem. With no problems it prints nothing and exits with 0.

go vet also checks _test.go files, which is where many t.Errorf format mistakes hide.

go vet runs during go test

You get some vet checking for free: go test runs a high-confidence subset of the analyzers before building the test binary. If one of them reports a problem, the tests don't run.

The subset is atomic, bools, buildtag, directive, errorsas, ifaceassert, nilfunc, printf, stdversion, stringintconv and tests. Those checks have almost no false positives, so a failure is always worth fixing.

Here's a test file with three mistakes:

package mathx

import (
	"fmt"
	"testing"
)

func TestSum(t *testing.T) {
	if got := Sum(1, 2, 3); got != 6 {
		t.Errorf("Sum = %s, want 6", got)
	}
}

// Not run: the name after "Test" must not start with a lower-case letter.
func Testsum(t *testing.T) {}

func TestSumParallel(t *testing.T) {
	go func() {
		if Sum(1) != 1 {
			t.Fatal("bad sum")
		}
	}()
}

func ExampleSumm() {
	fmt.Println(Sum(1, 2))
	// Output: 3
}
$ go test
# example.com/vetdemo/mathx
# [example.com/vetdemo/mathx]
./sum_test.go:10:19: (*testing.common).Errorf format %s has arg got of wrong type int
./sum_test.go:15:6: Testsum has malformed name: first letter after 'Test' must not be lowercase
./sum_test.go:25:1: ExampleSumm refers to unknown identifier: Summ
FAIL	example.com/vetdemo/mathx [build failed]

The tests analyzer (part of go test since Go 1.24) catches tests that would silently never run: Testsum isn't a test at all, and ExampleSumm documents a function that doesn't exist.

go test didn't report the t.Fatal called from a goroutine, because testinggoroutine isn't in the subset. A full go vet finds it:

$ go vet
sum_test.go:10:19: (*testing.common).Errorf format %s has arg got of wrong type int
sum_test.go:20:4: call to (*testing.T).Fatal from a non-test goroutine
sum_test.go:15:6: Testsum has malformed name: first letter after 'Test' must not be lowercase
sum_test.go:25:1: ExampleSumm refers to unknown identifier: Summ

go test has a -vet flag:

go test -vet=off ./...          # skip vet entirely
go test -vet=all ./...          # run every analyzer, like go vet
go test -vet=printf,tests ./... # run only these

-vet=off is occasionally useful to run tests while you're in the middle of a change, but don't leave it in CI. Running go vet ./... as a separate CI step is better than -vet=all because it also checks packages that have no tests.

Note that the output order isn't sorted by line. go vet groups diagnostics by analyzer, not by position.

Format strings: printf

The printf analyzer knows fmt.Printf, fmt.Sprintf, fmt.Errorf, log.Printf, t.Errorf and the rest. It checks that verbs match argument types and that the number of arguments is right.

It also figures out which of your functions are printf wrappers. A function that takes format string, args ...any and passes them on to a printf-like function gets checked at its call sites too:

package main

import (
	"fmt"
	"log"
)

// logf is detected as a printf wrapper because it forwards
// format and args to fmt.Sprintf.
func logf(format string, args ...any) {
	log.Print("app: " + fmt.Sprintf(format, args...))
}

func debugf(format string, args ...any) {
	fmt.Printf(format, args)
}

func main() {
	logf("user %s logged in", 42)
	debugf("%d items\n", 3)
	s := fmt.Sprintf("%v", logf)
	_ = s
	fmt.Println("done\n")
	fmt.Println("x = %d", 5)
}
$ go vet
main.go:15:2: missing ... in args forwarded to printf-like function
main.go:19:13: example.com/vetdemo/wrap.logf format %s has arg 42 of wrong type int
main.go:21:20: fmt.Sprintf format %v arg logf is a func value, not called
main.go:23:2: fmt.Println arg list ends with redundant newline
main.go:24:2: fmt.Println call has possible Printf formatting directive %d

debugf forgot the ... when forwarding args, so the whole slice is passed as a single argument. Variadic parameters explains this mistake in detail.

Non-constant format strings (Go 1.24)

fmt.Printf(msg) works until msg contains a %. Since Go 1.24 printf reports a call whose format is a variable and that has no other arguments. The fix is fmt.Printf("%s", msg), or fmt.Print(msg).

This check only applies to files whose module says go 1.24 or later in go.mod, so upgrading the toolchain alone doesn't suddenly break builds of old code.

%w with a pointer to an error (Go 1.27)

This is a subtle one:

package main

import (
	"errors"
	"fmt"
)

type NotFoundError struct{ Name string }

func (e NotFoundError) Error() string { return e.Name + " not found" }

func find(name string) error {
	e := &NotFoundError{Name: name}
	return fmt.Errorf("find: %w", e)
}

func main() {
	err := find("config")
	fmt.Println(errors.Is(err, NotFoundError{Name: "config"}))
}
false

NotFoundError has a value receiver, so both NotFoundError and *NotFoundError implement error. The code wraps a pointer, so errors.Is comparing against a NotFoundError value never matches, and neither does errors.As with a *NotFoundError target. Go 1.27 vet reports it:

main.go:14:27: %w wants operand of error type NotFoundError, not pointer type *NotFoundError (defeats errors.Is)

Wrap the value (%w with *e or NotFoundError{...}), or pick one receiver kind for your error type and use it consistently. See Custom error types.

errors.As needs a pointer: errorsas

The second argument of errors.As must be a pointer to a variable of an error type. Getting it wrong compiles, then panics at runtime:

	_, err = os.Open("missing.txt")
	var pe fs.PathError
	if errors.As(err, pe) { // should be &pe, and pe should be *fs.PathError
		fmt.Println("path:", pe.Path)
	}
panic: errors: target must be a non-nil pointer
main.go:25:5: second argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface type

The correct version is var pe *fs.PathError and errors.As(err, &pe), because *fs.PathError is the type that implements error.

Locks, goroutines and contexts

package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

type Counter struct {
	mu sync.Mutex
	n  map[string]int
}

// Value receiver: every call works on a copy of the mutex.
func (c Counter) Get(key string) int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.n[key]
}

func process(items []string) {
	var wg sync.WaitGroup
	for _, it := range items {
		go func() {
			wg.Add(1)
			defer wg.Done()
			fmt.Println(it)
		}()
	}
	wg.Wait()
}

func fetch() error {
	ctx, _ := context.WithTimeout(context.Background(), time.Second)
	<-ctx.Done()
	return ctx.Err()
}

func timed() {
	start := time.Now()
	defer fmt.Println("took", time.Since(start))
	time.Sleep(10 * time.Millisecond)
}

func main() {
	c := Counter{n: map[string]int{}}
	c2 := c
	fmt.Println(c2.Get("a"))
	process([]string{"a", "b"})
	_ = fetch()
	timed()
}
$ go vet
main.go:35:7: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak
main.go:26:10: WaitGroup.Add called from inside new goroutine
main.go:16:9: Get passes lock by value: example.com/vetdemo/locks.Counter contains sync.Mutex
main.go:48:8: assignment copies lock value to c2: example.com/vetdemo/locks.Counter contains sync.Mutex
main.go:42:28: call to time.Since is not deferred

Five analyzers, five bugs:

Before Go 1.22 there was also the classic loop variable capture bug, which the loopclosure analyzer reported. Since Go 1.22 each iteration gets a new variable and loopclosure only checks files in modules older than that. See Common pitfalls.

Misusing the standard library

A grab bag of mistakes vet knows about:

package main

import (
	"encoding/json"
	"fmt"
	"net"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"time"
)

type User struct {
	Name  string `json:"name"`
	Email string `json: "email"`
	Age   int    `json:"name"`
}

func get(url string) (int, error) {
	resp, err := http.Get(url)
	defer resp.Body.Close()
	if err != nil {
		return 0, err
	}
	return resp.StatusCode, nil
}

func dial(host string, port int) (net.Conn, error) {
	addr := fmt.Sprintf("%s:%d", host, port)
	return net.Dial("tcp", addr)
}

func main() {
	var u User
	json.Unmarshal([]byte(`{"name":"ann"}`), u)

	s := "  hello "
	strings.TrimSpace(s)
	fmt.Sprintf("%s!", s)

	day := time.Now().Format("2006-02-01")
	fmt.Println(day)

	n := 65
	fmt.Println(string(n))

	if n != 1 || n != 2 {
		fmt.Println("always true")
	}

	var names []string
	names = append(names)

	sig := make(chan os.Signal)
	signal.Notify(sig, os.Interrupt)
	_, _ = get, dial
}
$ go vet
main.go:53:10: append with no values
main.go:30:22: address format "%s:%d" does not work with IPv6 (passed to net.Dial at L31)
main.go:56:2: misuse of unbuffered os.Signal channel as argument to signal.Notify
main.go:46:14: conversion from int to string yields a string of one rune, not a string of digits
main.go:42:28: 2006-02-01 should be 2006-01-02
main.go:40:2: result of fmt.Sprintf call not used
main.go:48:5: suspect or: n != 1 || n != 2
main.go:22:8: using resp before checking for errors
main.go:16:2: struct field tag `json: "email"` not compatible with reflect.StructTag.Get: bad syntax for struct tag value
main.go:17:2: struct field Age repeats json tag "name" also at main.go:15
main.go:36:16: call of Unmarshal passes non-pointer as second argument
Analyzer What it caught Fix
appends append(names) adds nothing add the missing values
hostport (1.25) "%s:%d" breaks for IPv6 addresses like ::1 net.JoinHostPort(host, strconv.Itoa(port))
sigchanyzer a signal sent before you receive is dropped make(chan os.Signal, 1)
stringintconv string(65) is "A", not "65" strconv.Itoa(n), or string(rune(n)) if you meant a rune
timeformat the layout has month and day swapped "2006-01-02" (or time.DateOnly)
unusedresult fmt.Sprintf result thrown away use the result
bools n != 1 || n != 2 is always true you meant &&
httpresponse resp is nil when err != nil, so the defer panics check err first, then defer resp.Body.Close()
structtag space after json:, duplicate JSON name json:"email", unique names
unmarshal Unmarshal can't fill a copy pass &u

Note what vet did not report: strings.TrimSpace(s) with the result ignored. unusedresult only knows a fixed list of functions (fmt.Sprintf, errors.New, most of slices and maps, context.WithCancel...), see go tool vet help unusedresult. Struct tags are explained in Struct tags.

Two more worth knowing:

	slog.Info("user logged in", "id", 42, "name")

	addr := net.TCPAddr{net.ParseIP("127.0.0.1"), 8080, ""}
main.go:12:10: net.TCPAddr struct literal uses unkeyed fields
main.go:10:2: call to slog.Info missing a final value

slog checks that key-value pairs passed to log/slog come in pairs. Without vet, the program logs !BADKEY=name (see Structured logging with log/slog). composites reports unkeyed literals of structs from other packages, which break when that package adds a field. It doesn't complain about your own package's types.

Using too-new APIs: stdversion

The go line in go.mod says which Go version your module supports. A newer toolchain compiles calls to newer APIs just fine, so you won't notice until someone builds with the older Go version you claim to support.

stdversion (Go 1.23) catches this. With go 1.22 in go.mod:

package main

import (
	"fmt"
	"maps"
	"slices"
	"sync"
)

func main() {
	ages := map[string]int{"bob": 31, "ann": 25}
	names := slices.Sorted(maps.Keys(ages))
	fmt.Println(names)

	var wg sync.WaitGroup
	wg.Go(func() { fmt.Println("hi") })
	wg.Wait()
}
$ go vet
main.go:12:18: slices.Sorted requires go1.23 or later (module is go1.22)
main.go:12:30: maps.Keys requires go1.23 or later (module is go1.22)
main.go:16:5: sync.(*WaitGroup).Go requires go1.25 or later (module is go1.22)

go build with Go 1.27 succeeds, and so would the program. Either raise the go line or avoid the new functions. Since stdversion is in the go test subset, go test fails on it too. A single file can opt in to a newer version with a //go:build go1.25 constraint at the top.

Selecting analyzers

By default go vet runs all its analyzers. List them, and read the documentation of one:

go tool vet help
go tool vet help copylocks

Pass -NAME to run only the listed analyzers, or -NAME=false to run everything except them:

$ go vet -printf
main.go:10:14: fmt.Printf format %s has arg count of wrong type int
main.go:11:21: fmt.Printf format %d reads arg #1, but call has 0 args
main.go:14:13: non-constant format string in call to fmt.Printf
$ go vet -printf=false
main.go:18:3: unreachable code

Turning off a check for a whole project should be rare. go vet has no //nolint-style comment to silence one line; if a report really is a false positive, rewrite the code so the intent is clear (for example fmt.Print(msg) instead of fmt.Printf(msg)).

If your printf wrapper isn't detected automatically, for example because it's an interface method, list it with -printf.funcs:

go vet -printf.funcs=Logf,Debugf ./...

-c=N prints N lines of context around each problem:

$ go vet -c=1 -unreachable
main.go:18:3: unreachable code
17			return
18			fmt.Println("unreachable")
19		}

Applying suggested fixes

Some diagnostics come with a suggested fix. -fix applies them; -fix -diff shows the patch without changing files and exits with status 1 if there's anything to fix:

$ go vet -fix -diff
--- /home/me/vetdemo/first/main.go (old)
+++ /home/me/vetdemo/first/main.go (new)
@@ -11,10 +11,9 @@
 	fmt.Printf("total: %d\n")
 
 	msg := "100% done"
-	fmt.Printf(msg)
+	fmt.Printf("%s", msg)
 
 	if len(os.Args) > 5 {
 		return
-		fmt.Println("unreachable")
 	}
 }

The wrong %s/%d arguments had no fix: vet can't know what you meant. The hostport analyzer suggests net.JoinHostPort:

$ go vet -hostport -fix -diff
...
-	addr := fmt.Sprintf("%s:%d", host, port)
+	addr := net.JoinHostPort(host, fmt.Sprintf("%d", port))

Review the diff before applying. Deleting unreachable code is right here, but sometimes the bug is the return above it. For rewriting working code to newer idioms, use go fix and modernizers instead: go vet reports likely bugs, go fix modernizes.

JSON output

-json prints the diagnostics as JSON, grouped by package and analyzer, for tools that process them (paths are absolute; shortened here):

$ go vet -json
{
	"example.com/vetdemo/first": {
		"printf": [
			{
				"posn": "/home/me/vetdemo/first/main.go:14:13",
				"end": "/home/me/vetdemo/first/main.go:14:16",
				"message": "non-constant format string in call to fmt.Printf",
				"suggested_fixes": [
					{
						"message": "Insert \"%s\" format string",
						"edits": [
							{
								"filename": "/home/me/vetdemo/first/main.go",
								"start": 185,
								"end": 185,
								"new": "\"%s\", "
							}
						]
					}
				]
			}
		],
		...
	}
}

start and end are byte offsets in the file. Be careful in CI: with -json, go vet exits with status 0 even when it found problems. Your script must check whether the output contains any diagnostics.

Extra analyzers: shadow

go vet ships only checks with few false positives. More analyzers live in golang.org/x/tools, and you can run any analyzer built with unitchecker through go vet -vettool. The best known is shadow, which reports variables declared with := that hide an outer variable of the same name:

package main

import (
	"errors"
	"fmt"
	"os"
)

func load(path string) (data []byte, err error) {
	if path == "" {
		return nil, errors.New("empty path")
	}
	if _, err := os.Stat(path); err == nil {
		data, err := os.ReadFile(path)
		if err != nil {
			return nil, err
		}
		fmt.Println("read", len(data), "bytes")
	}
	return data, err
}

func main() {
	data, err := load("main.go")
	fmt.Println(len(data), err)
}
read 415 bytes
0 <nil>

The file was read, but load returns no data: data, err := inside the if created new variables. Install and run shadow:

$ go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest
$ go vet -vettool=$(which shadow)
main.go:13:8: declaration of "err" shadows declaration at line 9
main.go:14:3: declaration of "data" shadows declaration at line 9

-strict also reports shadowing where the outer variable isn't used afterwards:

$ go vet -vettool=$(which shadow) -strict
main.go:13:8: declaration of "err" shadows declaration at line 9
main.go:14:3: declaration of "data" shadows declaration at line 9
main.go:14:9: declaration of "err" shadows declaration at line 13

shadow is noisy (shadowing err is often intentional), which is why it isn't part of the default set. Note that -vettool replaces the standard analyzers, so run plain go vet ./... as well.

On Windows, outside of a Unix-like shell, pass the full path to shadow.exe instead of $(which shadow). go install puts it in go env GOBIN, or in go\bin under your home directory if GOBIN isn't set.

For a much larger set of checks, look at staticcheck (go tool staticcheck ./... after adding it as a tool dependency) or golangci-lint, which bundles vet, staticcheck and dozens of other linters.

In CI

Add a vet step next to your tests:

go vet ./...
go test ./...

Test Go code with GitHub Actions shows a complete workflow.

What vet doesn't catch

Vet looks at code patterns, not at what happens at runtime. It won't find:

Treat a clean go vet as the minimum bar, not a proof of correctness.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents