On Mon, Feb 11, 2019 at 5:48 PM Slawomir Pryczek <slawek1...@gmail.com> wrote:
>
> Hi Guys,
>
> 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?


This is well-documented behavior. The first link I can find is:
https://github.com/golang/go/wiki/CommonMistakes

The common mistake is to think that the for-loop variable is captured
as value in the closure. It is not, it is a reference, and the
go-routine sees the value of the variable when it runs, not when it is
created.

>
> https://play.golang.org/p/6vx_qDOk51g
>
> 10 1
> 10 0
> 10 9
> 10 8
> 10 7
> 10 6
> 10 5
> 10 4
> 10 3
> 10 2
>
>
> Thanks,
> Slawomir.
>
>
> -----
> package main
> import (
> "fmt"
> "time"
> )
>
> func main() {
> for i := 0; i < 10; i++ {
> t := i
> go func() {
> time.Sleep(time.Millisecond * 100)
> fmt.Println(i, t)
> }()
> }
> time.Sleep(time.Millisecond * 1000)
> }
>
>
>
> --
> 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.

Reply via email to