I am seeing incorrect values in the functions run as goroutines. They don't seem to be capturing the values from the scope in which they were invoked unless copied into new variables.
http://play.golang.org/p/YZYi-IVuYm
vs.
I am seeing incorrect values in the functions run as goroutines. They don't seem to be capturing the values from the scope in which they were invoked unless copied into new variables.
http://play.golang.org/p/YZYi-IVuYm
vs.
You either need to re-assign the variable in the local context so that the closure can capture the values:
http://play.golang.org/p/-NO4S4qCZf
package main
import "fmt"
import "time"
func main() {
l := []int{1, 2, 3}
for idx, item := range l {
theIdx, theItem := idx, item
go func() {
fmt.Println(theIdx, theItem)
}()
}
time.Sleep(time.Second)
}
or you pass the values to the goroutine and add parameters to the function
http://play.golang.org/p/5gNToDWSQR
package main
import "fmt"
import "time"
func main() {
l := []int{1, 2, 3}
for idx, item := range l {
go func(idx, item int) {
fmt.Println(idx, item)
}(idx, item)
}
time.Sleep(time.Second)
}