考慮以下 Go 代碼(也在Go Playground 上):package mainimport "fmt"import "time"func main() { for _, s := range []string{"foo", "bar"} { x := s func() { fmt.Printf("s: %s\n", s) fmt.Printf("x: %s\n", x) }() } fmt.Println() for _, s := range []string{"foo", "bar"} { x := s go func() { fmt.Printf("s: %s\n", s) fmt.Printf("x: %s\n", x) }() } time.Sleep(time.Second)}此代碼產(chǎn)生以下輸出:s: foox: foos: barx: bars: barx: foos: barx: bar假設(shè)這不是一些奇怪的編譯器錯誤,我很好奇為什么 a) s 的值在 goroutine 版本和常規(guī) func 調(diào)用中的解釋不同,以及 b) 為什么將它分配給循環(huán)內(nèi)的局部變量有效兩種情況。
- 2 回答
- 0 關(guān)注
- 198 瀏覽
添加回答
舉報
0/150
提交
取消