結論:
閉包能夠訪問外層代碼中的變量;
foe循環(huán)與gotoutine同時執(zhí)行挂滓;
所有的goroutine操作的變量都是直接操作外層代碼的變量馒索,而外層代碼中的變量的值取決于循環(huán)執(zhí)行的節(jié)點岖食。
正確代碼:
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