Why does this fail (all the time prints 3
)
func major() {
for i := 0; i < 3; i++ {
go func() {
fmt.Println(i)
}()
}
time.Sleep(1 * time.Second)
}
whereas this works?
func major() {
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 major() {
for i := 0; i < 3; i++ {
go func(i int) {
fmt.Println(i)
}(i)
}
time.Sleep(1 * time.Second)
}
Extra information
https://eli.thegreenplace.internet/2019/go-internals-capturing-loop-variables-in-closures/
You need to use go vet to keep away from this points
Or go lint (consists of go vet)