This is mentioned directly in the language specification under For statements with range clause <https://golang.org/ref/spec#For_range>:
For each entry it assigns iteration values to corresponding iteration > variables if present and then executes the block. and > For an array, pointer to array, or slice value a, the index iteration > values are produced in increasing order, starting at element index 0. If at > most one iteration variable is present, the range loop produces iteration > values from 0 up to len(a)-1 and does not index into the array or slice > itself. For a nil slice, the number of iterations is 0. This seems logically correct to me, as well. For an array or slice of len(array) = N, the for range statement generates N iteration values, starting from 0. The Nth iteration value would have to be N-1. The difference in semantics is because the post statement in a for loop must be executed after the body is executed. A typical for-loop assigns the N+1st iteration value to the iteration variable, but that is a user's choice. Hopefully that is more clear, Chris On Tue, Jul 25, 2017 at 3:30 PM, 'Axel Wagner' via golang-nuts < golang-nuts@googlegroups.com> wrote: > Hey, > > someone shared [this question](https://www.reddit. > com/r/golang/comments/6paqc0/bug_that_caught_me_with_range/) on reddit. I > must say, that I'm surprised by the behavior myself. I would have expected > for i = range v > to be semantically equivalent to > for i = 0; i < len(v); i++ > and don't really understand the reasoning behind choosing different > semantics. Note, that the difference only exists, if i is declared outside > of the loop, that is, this is solely about the behavior after exiting the > loop-body. > > I'd greatly appreciate some explanation :) > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.