Hi Axel,

An attempt to explain this by looking at the C-style loop only:

The classic C-style for loop

for i:=0; i<len(v); i++ {...}

is equivalent to

for i:=0; i<len(v); {
    // do something with i
    i++ // This is always the very last statement in the loop body
}


The loop body runs from 0 to len(v)-1 only, because the last increment of i 
to len(v) stops the loop, and no further iteration occurs. The code in the 
loop body never sees i being set to len(v). 

And that's the same behavior as with the range operator. 

The code in the Reddit post takes advantage of the fact that the last 
increment of the C-style loop can be observed outside the loop, for 
detecting if the loop stopped early. This is a neat side effect that is not 
possible with the range operator.

On Wednesday, July 26, 2017 at 12:30:28 AM UTC+2, Axel Wagner 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.

Reply via email to