Consider the following Go code (also on the Go Playground):
package main
import "fmt"
import "time"
func main() {
for _, s := range []string{"foo", "bar"} {
x := s
func() {
fmt.Printf("s: %s
", s)
fmt.Printf("x: %s
", x)
}()
}
fmt.Println()
for _, s := range []string{"foo", "bar"} {
x := s
go func() {
fmt.Printf("s: %s
", s)
fmt.Printf("x: %s
", x)
}()
}
time.Sleep(time.Second)
}
This code produces the following output:
s: foo
x: foo
s: bar
x: bar
s: bar
x: foo
s: bar
x: bar
Assuming this isn't some odd compiler bug, I'm curious why a) the value of s is interpreted differently in the goroutine version then in the regular func call and b) and why assigning it to a local variable inside the loop works in both cases.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…