Does anybody know why the case1 output the same result, but the case2 output the sequential result? I know the reason why case1 output the same value is that the closure of each function in functions slice access to the same scope.
But why after adding i:=i in each loop can case2 output the sequential result? Does after redefining i in eachloop, a new scope is generated? like let in javascript?
case1
func main() {
funcs := []func() {}
for i:=0;i<10;i++{
funcs = append(funcs, func() {
fmt.Println(i)
})
}
for i:=0;i<10;i++{
funcs[i]()
}
}
output
10
10
10
10
10
10
10
10
10
10
case2
func main() {
funcs := []func() {}
for i:=0;i<10;i++{
i := i
funcs = append(funcs, func() {
fmt.Println(i)
})
}
for i:=0;i<10;i++{
funcs[i]()
}
}
output
0
1
2
3
4
5
6
7
8
9