The following program
package main
import (
"fmt"
)
type TestFunc func()
func main() {
fmt.Println()
funcs := []TestFunc{}
for i:=0; i<5; i++ {
//i := i
funcs = append(funcs, func() {fmt.Println(i)})
}
for _, f := range funcs {
f()
}
}
produces an output 5, 5, 5, 5, 5. After uncommenting the line, the program
for i:=0; i<5; i++ {
i := i
funcs = append(funcs, func() {fmt.Println(i)})
}
for _, f := range funcs {
f()
}
produces an output 0, 1, 2, 3, 4.
Is there a better (or an idiomatic) way to pass the current value to a function declaration instead of using i := i
?