Why does this fail (at all times prints 3
)
func predominant() {
for i := 0; i < 3; i++ {
go func() {
fmt.Println(i)
}()
}
time.Sleep(1 * time.Second)
}
whereas this works?
func predominant() {
for i := 0; i < 3; i++ {
func() {
go fmt.Println(i)
}()
}
time.Sleep(1 * time.Second)
}
As a result of on the time the go routines are scheduled, i
is 3.
If you wish to use outer values in a goroutine, cross them when creating the goroutine:
func predominant() {
for i := 0; i < 3; i++ {
go func(i int) {
fmt.Println(i)
}(i)
}
time.Sleep(1 * time.Second)
}