package main
import (
"fmt"
)
func main() {
a := []int{1, 2, 3}
var fs []func()
for idx, x := range a {
f := func() {
fmt.Println(idx, " ", x)
}
fs = append(fs, f)
}
for _, f := range fs {
f()
}
}
I have this piece of code. The output of this code is
2 3
2 3
2 3
Which isn't matched my expectation
0 1
1 2
2 3
As I guest is that after the for loop, the ref of idx and x will point to the last element of array a and the function is executed after this for loop so it will print out 2 3 for an fs[i].