Go疑问-1
package main import ( "fmt" ) func main() { var numbers = make([]int, 0) ch := make(chan int, 100) count := 10 for i := 0; i < count; i++ { go func() { fmt.Printf("i = %d\n",i) ch <- i }() } visit := 0 for num := range ch { fmt.Printf("num = %d\n",num) numbers = append(numbers, num) visit++ if visit == count { break } } fmt.Println(len(numbers)) }
输出:
i = 2
i = 7
i = 7
i = 7
i = 8
i = 10
num = 7
i = 10
num = 7
num = 7
num = 8
num = 10
i = 10
num = 10
num = 10
i = 3
i = 3
num = 10
num = 10
num = 10
10
但:如果把goroutine的匿名函数改成常规有名函数,就输出正常,何故?闭包?