On Mon, Feb 11, 2019 at 4:48 PM Slawomir Pryczek <
slawe...@gmail.com> wrote:
>
> When looking at this code below, you can see that the function will get LAST value of i which is incremented inside the loop, but t is somehow copied and taken inside a function so closure is created and it is bound to current value of t, so we'll have its current value in function. This is strange as t and i is defined on the same code block level (t will be discarded at the same time as i, after the loop).
>
> I always thought that t would need to be passed explicitly to goroutine to retain current value (which i did). But why assigning value in a loop is treated differently in this regard than a straight assignment? Any URL where such "special cases" are documented? Isn't it kind of design flaw, because this seem very confusing that loop is creating single value and simple assignment is creating multiple copies? Maybe you consider changing this in go2?
A nested function that refers to a variable outside the closure is
always using a reference to that variable, never a copy. So the only
question here is about the handling of variables in a loop. The rule
is simply that a new variable is created at each variable declaration.
In the loop, there is one variable declaration of i when the loop
starts: i := 0. The other references to i, including all the uses of
i within the loop, all refer to that single variable. But the
declaration "t := i" is declared each time through the loop, so each
separate iteration of the loop has a different variable t.
So there is no special case here, and this is working as intended.
Hope this helps.
Ian