You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
The value type is the same as the index.
sum:=0forn:=range []int{5, 6} {
sum+=n
}
The value type is different from the index type, but is used in a type-ambiguous context such as an empty interface.
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:
sum:=0forn, _:= []int{5, 6} {
sum+=n
}
Now it is clear that n is the index.
The text was updated successfully, but these errors were encountered:
ianlancetaylor
changed the title
go vet should require unpacking both range variables in a for loop
cmd/vet: should require unpacking both range variables in a for loop
Aug 1, 2017
That's fair, and I appreciate the feedback, thank you! I was wondering if the following scenario is worth discussing:
In the case of:
nums:= []int{5, 6}
forn:=rangenums {
// ...
}
whether or not n is being used as an index (e.g. nums[n]) in the loop.
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 go vet. However, I do think this can be a very difficult bug to detect without some tooling and Go programmers would benefit from this situation being flagged.
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: