cmd/vet: should require unpacking both range variables in a for loop #21250
Comments
I think that would issue a warning on too much existing, correct, code. See cmd/vet/README for the criteria for vet checks. |
I agree with @ianlancetaylor. Perhaps you should propose this as a Go2 language change. |
That's fair, and I appreciate the feedback, thank you! I was wondering if the following scenario is worth discussing: nums := []int{5, 6}
for n := range nums {
// ...
} whether or not I'm unsure if this should be something that is checked by the compiler for Go2 or if this would fulfill the correctness/frequency/precision criteria for |
Correct code and incorrect code are basically indistinguishable in this case. The way to find this bug is to run the code and have a test, not to make vet guess which is meant. |
Problem
When iterating over a slice or a map using range, the programmer has the option of unpacking only the index, or both index and the value. In cases where only the value is needed, it is easy to forget to also unpack the index into a throwaway variable. In particular, there are two cases where the compiler cannot catch this mistake:
Proposed Solution
We are proposing that
go vet
require the unpacking of both values so the programmer must be explicit when using range. This will make mistakes like the above examples more obvious, for example:Now it is clear that
n
is the index.The text was updated successfully, but these errors were encountered: