为什么我的 Golang for 循环中的 range 无法正确迭代?

huangapple go评论82阅读模式
英文:

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

问题

我很困惑为什么以下代码没有打印出迭代的值。

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

我认为它应该打印出:

0 0
1 1
2 2
3 3 
4 4

但实际上,它打印出了:

4 4
4 4
4 4
4 4
4 4
英文:

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

得分: 10

你的 goroutine 并没有捕获变量 iv 的当前值,而是引用了这些变量本身。在这种情况下,5个被创建的 goroutine 直到 for 循环结束后才被调度,所以它们都打印出了 iv 的最后一个值。

如果你想要在 goroutine 中捕获某些变量的当前值,你可以修改代码如下:

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

现在每个 goroutine 都有自己的变量副本,保存了它被创建时的值。

英文:

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.

huangapple
  • 本文由 发表于 2014年2月17日 14:49:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/21822527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定