如何在goroutine中使用正确的值? 使用goroutine在语义上令人困惑,并且无法按预期方式作为附件使用。
package main
import (
"fmt"
"time"
)
func main() {
a := []int{1,2,3,4,5,6}
for i, _ := range a {
if a[i] % 2 == 1 {
go func() {
fmt.Println(a[i])
}()
} else {
go func() {
fmt.Println(a[i])
}()
}
}
for j, _:= range a {
go func() {
fmt.Println(a[j])
}()
}
time.Sleep(time.Second * 2)
}
//output 6 6 6 6 6 6 6 6 6...