Why golang don't iterate correctly in my for loop with range?

偶尔善良 提交于 2020-01-05 04:06:08

问题


I am confused why the following code does not print out iterated value.

test:= []int{0,1,2,3,4}
for i,v := range test{
  go func(){
    fmt.Println(i,v)
  }
}

What I think is that it should print out

0 0
1 1
2 2
3 3 
4 4

But instead, it printed out

4 4
4 4
4 4
4 4
4 4

回答1:


Your goroutines don't capture the current value of the variables i and v, but rather they reference the variables themselves. In this case, the 5 spawned goroutines did not get scheduled until the for loop finished, so all printed out the last values of i and v.

If you want to capture the current values of some variables for the gouroutine, you could modify the code to read something like the following:

go func(i, v int){
    fmt.Println(i,v)
}(i, v)

Now each gouroutine has its own copy of the variables holding the value at the time it was spawned.



来源:https://stackoverflow.com/questions/21822527/why-golang-dont-iterate-correctly-in-my-for-loop-with-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!