试试下面的几个例子,并反思总结。
1、
package main
import (
"fmt"
"runtime"
)
func main() {
names:=[]string{"A","B","C","D"}
for _,name := range names{
go func() {
fmt.Printf("Hello %s \n",name)
}()
runtime.Gosched()
}
}
2、
package main
import (
"fmt"
"runtime"
)
func main() {
names:=[]string{"A","B","C","D"}
for _,name := range names{
go func() {
fmt.Printf("Hello %s \n",name)
}()
}
runtime.Gosched()
}
3、package main
import (
"fmt"
"runtime"
)
func main() {
names:=[]string{"A","B","C","D"}
for _,name := range names{
go func(who string) {
fmt.Printf("Hello %s \n",who)
}(name)
}
runtime.Gosched()
}
执行的结果,很显然3是正确的,原因在于name变量的类型是一个非引用类型。我们将name传递至方法时,值会被复制。
而切片是引用类型,改变其值会对函数内部产生影响,所以使用3的形式,达到“分离”的效果。