New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
cmd/vet: warn about unconditional return in a loop #22534
Comments
The guidelines for vet checks (see cmd/vet/README) are frequency, correctness, and precision. This test is precise, but I doubt it is frequent. It is also not always correct; some code chooses a random key from a map by writing
So I don't think this meets the criteria for adding to cmd/vet. |
For correctness, the check can easily be improved to recognize that pattern, which is what staticcheck does. However, this still leaves the possibility for contrived code that is correct but strange. As for frequency, you're correct. It does occur in real code, but not very often. (Pedantry: it's an arbitrary key, not a random one) |
Care to explain? I know map ranges aren't truly random, but you should still get a semi-random key from the set of keys. |
@mvdan The spec leaves the order undefined. The order could well be insertion order or alphabetical order or some other order. And even in this implementation, the distribution of random iteration isn't very good. IOW, if you want to get some key (i.e. arbitrary), the one-iteration loop is fine. If you want a random key – one that is chosen fairly – it is not fine. |
(The most common place where I've seen this kind of code is where you know the map has 1 element and you want to get it out.) |
@ianlancetaylor The code below is perfect and meant to run only once and returns some key of the map
I opened this issue about the case below where the code is supposed to run multiple times in the loop but does not due to the unconditional
Yes, this code may not be common, is mostly a mistake, but could be caught by |
@vhosakot If the problem is not common, it shouldn't go into vet. There are other static checking tools that have different criteria. |
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes.
What operating system and processor architecture are you using (
go env
)?MacOS Seirra.
What did you do?
Ran
go tool vet
on the following code that has an unconditionalreturn
inside afor
loop:What did you expect to see?
An error or a warning that the loop exits unconditionally after just one iteration similar to the error
SA4004 The loop exits unconditionally after one iteration
in the Gostaticcheck
tool in https://staticcheck.io/docs/staticcheck.What did you see instead?
No error or warning.
The text was updated successfully, but these errors were encountered: