package main
import (
"fmt"
"time"
)
func main() {
names := []string{"Eric", "Harry", "Robert", "Jim", "Mark"}
for _, name := range names {
go func() {
fmt.Printf("Hello, %s!\n", name)
}()
}
time.Sleep(time.Millisecond)
}
结果:
package main
import (
"fmt"
"time"
)
func main() {
names := []string{"Eric", "Harry", "Robert", "Jim", "Mark"}
for _, name := range names {
go func() {
fmt.Printf("Hello, %s!\n", name)
}()
}
time.Sleep(time.Millisecond)
}
package main
import (
"fmt"
"time"
)
func main() {
names := []string{"Eric", "Harry", "Robert", "Jim", "Mark"}
for _, name := range names {
go func(who string) {
fmt.Printf("Hello, %s!\n", who)
}(name)
}
time.Sleep(time.Millisecond)
}
结果:
package main
import (
"fmt"
"time"
)
func main() {
names := []string{"Eric", "Harry", "Robert", "Jim", "Mark"}
for _, name := range names {
go func(who string) {
fmt.Printf("Hello, %s!\n", who)
}(name)
}
time.Sleep(time.Millisecond)
}
为什么第二段就能正常的迭代了呢?
1
Adia OP up
|
2
CuminLo 2017-06-17 10:36:17 +08:00
没看懂?结果是?
|
3
Yoock 2017-06-18 18:16:49 +08:00
我觉得原因可能是每次 for range k 和 v 不是新建变量,而是变量复用。
所以每次不指定输出的字符串,并发输出 v 的话,都会变成最后一次 v 的值。 说的有点乱,希望你可以理解。 |
4
xinQing 2018-01-25 16:29:49 +08:00
闭包问题
|