Go: Vet Command Is More Powerful Than You Think

Vincent
A Journey With Go
Published in
4 min readAug 1, 2019

--

Illustration created for “A Journey With Go”, made from the original Go Gopher, created by Renee French.

Go vet command is a great help while writing your code. It helps you detect any suspicious, abnormal, or useless code in your application. The command is actually composed of several sub analyzers and could even work with your custom analyzer. Let’s review first the built-in analyzer.

Built-in analyzers

The list of the build-in analyzers is available from the command go tool vet help. Let’s analyze the less obvious ones to get a better understanding.

atomic

This analyzer will prevent any irregular usage of the atomic function

func main() {
var a int32 = 0

var wg sync.WaitGroup
for i := 0; i < 500; i++ {
wg.Add(1)
go func() {
a = atomic.AddInt32(&a, 1)
wg.Done()
}()
}
wg.Wait()
}
main.go:15:4: direct assignment to atomic value

The variable a is incremented thanks to the atomic memory primitives function addInt that is concurrent-safe. However, we assign the result to the same variable, which is a not a concurrent-safe write operation. This a careless mistake detected by the atomic analyzer.

copylocks

A lock should never be copied, as explained in the documentation. Indeed, internally it…

--

--