为什么Golang在我的for循环中没有正确迭代范围? [英] Why golang don't iterate correctly in my for loop with range?
问题描述
我很困惑为什么下面的代码不能打印出迭代值.
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)
}
}
我认为它应该打印出来
0 0
1 1
2 2
3 3
4 4
但是,它打印出来了
4 4
4 4
4 4
4 4
4 4
推荐答案
您的goroutine不会捕获变量 i
和 v
的当前值,而是引用变量本身.在这种情况下,直到for循环完成时,才对5个生成的goroutine进行调度,因此全部打印出 i
和 v
的最后一个值.
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.
这篇关于为什么Golang在我的for循环中没有正确迭代范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!