英文:
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 并没有捕获变量 i
和 v
的当前值,而是引用了这些变量本身。在这种情况下,5个被创建的 goroutine 直到 for 循环结束后才被调度,所以它们都打印出了 i
和 v
的最后一个值。
如果你想要在 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论