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
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.
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")
return
fmt.Println("This line will never be executed")
}
When running the vet command on this code we will get this result.
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,
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
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
that will output a short explanation on what it looks for and an example.
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!