Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
proposal: cmd/vet: missing error assignment check #19727
I noticed a mistake during a code review that I think could be automatically detected. The idea is to detect code which looks like:
which should instead assign the return value of f()
For the code to compile at all, err must be declared in the outer scope.
This check detects code that the programmer didn't intend to write. In some instances the mistake is caused by what I personally might call a readability issue, such as when f() is a multi-line func literal that obscures the if statement. Nevertheless, this reports on the missing assignment, not the style.
A number of these have been detected at Google. The check is lightweight. I did not do a large review of open-source Go, but examples can be seen at:
It is difficult to define a false negative for this test, but for my particular implementation perhaps errors that are not called "err", and are not checked against nil. Others implementations may be able to increase the scope.
False positives seem rare, though it is possible to write code like:
I do not think it would any less clear for f() to return err in that case though.
A false positive of my initial implementation is
this could be eliminated by looking for err (or &err) being passed as a parameter, though that function could avoid modifying its input parameter and instead return an error.
A more thorough check for if conditions that are always true/false would detect some of these situations, especially if a previous check for nil caused a return. But it would miss some, so I think a simple check is worth introducing. Some mistakes occur in tests:
whilst others aggregate errors rather than returning:
An initial implementation is here: https://go-review.googlesource.com/c/38631/
In this example:
there are two arguable problems:
The discussion on this issue focuses on detecting (1), which is pretty tricky. An alternative would be to detect (2), namely code that throws errors away without making that clear (without using