DEV Community

Cover image for The go vet command
Stefan Alfbo
Stefan Alfbo

Posted on

The go vet command

The go vet command is a tool that examines the source code and reports suspicious constructs that could be bugs or syntactical errors, a static analysis tool for Go programs.

This tool is part of the standard Go toolchain and therefore also easy to use when writing your code.

In its simplest form you just type following in the terminal.

go vet ./path/to/your/package

# or if the current directory is already the package
# directory, then you vet that package by just using:
go vet
Enter fullscreen mode Exit fullscreen mode

If we don't get any results then we do not have any vetting errors. Vet's exit code is non-zero for erroneous invocation of the tool or if a problem was reported, and 0 otherwise.

no vetting errors

Just to show how it would look like when the command complains, we could try it out on this function.

func HelloVet() {
    fmt.Println("Hello Vet")


    fmt.Println("This line will never be executed")
Enter fullscreen mode Exit fullscreen mode

When running the vet command on this code we will get this result.

vet error

An error, and it's just what we would expect, unreachable code. However from the go doc cmd/vet command we can read the following note,

Note that the tool does not check every possible problem and depends on unreliable heuristics, so it should be used as guidance only, not as a firm indicator of program correctness.

Which is good to remember when using the tool.

The tool makes it also possible to fine tune it if there are rules that do not fit your needs. For example if we do not care about unreachable code we could add that as flag,

fine tuning vet

now that error is not reported anymore and everything looks good again.

To list the registered analyzers you can use this command,

go tool vet help
Enter fullscreen mode Exit fullscreen mode

the list will include a bunch of analyzers. To learn more about a specific analyzer you can use the help system once again, for example the defers analyzer,

go tool vet help defers
Enter fullscreen mode Exit fullscreen mode

that will output a short explanation on what it looks for and an example.

defers help

So there are plenty of things to learn by just reading the Go documentation. According to the documentation it should also be possible to write your own checks for the vet command. Something that I haven't explored yet though.

So give the go vet command a try when you are coding some Go next time!

Happy vetting!

Top comments (0)