结论:
闭包能够访问外层代码中的变量;
foe循环与gotoutine同时执行;
所有的goroutine操作的变量都是直接操作外层代码的变量,而外层代码中的变量的值取决于循环执行的节点。
正确代码:
package main
import (
"fmt"
"sync"
)
func main() {
var s []string = []string{
"first",
"second",
"third",
}
var waitGroup sync.WaitGroup
waitGroup.Add(len(s))
for _, item := range s {
go func(i string) {
fmt.Println(item)
waitGroup.Done()
}(item)
}
waitGroup.Wait()
}
输出:
first
second
third
错误实例:
for _, item := range s {
go func() {
fmt.Println(item)
waitGroup.Done()
}()
}
输出:
third
third
third
通过以下实例能够解释上面出现的情况:
for _, item := range s {
go func() {
fmt.Println(item)
waitGroup.Done()
}()
time.Sleep(1 * time.Second)
}
输出:
third
third
third