考虑以下Golang代码(也在Go Playground上):
package main
import "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)
}
Run Code Online (Sandbox Code Playgroud)
此代码生成以下输出:
s: foo
x: foo
s: bar
x: bar
s: bar
x: foo
s: bar
x: bar
Run Code Online (Sandbox Code Playgroud)
假设这不是一些奇怪的编译器错误,我很好奇为什么a)s的值在goroutine版本中然后在常规func调用中被解释不同而b)以及为什么将它分配给循环内部的局部变量两种情况.