here is a snippet: https://play.golang.org/p/cKrC0oy7FP
package main
import (
"fmt"
"time"
)
type field struct {
name string
}
func (p *field) print() {
fmt.Println(p.name)
}
func TestClosure() {
data := []*field{{"one"}, {"two"}, {"three"}}
for _, v := range data {
go v.print()
}
time.Sleep(3 * time.Second)
}
func TestClosure1() {
data := []field{{"one"}, {"two"}, {"three"}}
for _, v := range data {
go v.print()
}
time.Sleep(3 * time.Second)
}
func TestClosure2() {
data := []*field{{"one"}, {"two"}, {"three"}}
for _, v := range data {
go func(){
v.print()
}()
}
time.Sleep(3 * time.Second)
}
func main(){
TestClosure() // two one three (one possible result)
fmt.Println("----")
TestClosure1() // three three three (always)
fmt.Println("----")
TestClosure2() // three three three (always)
}
The only difference between TestClosure() and TestClosure1() is data, a array of field or array of *field.
The difference between TestClosure1() and TestClosure2() is the way goroutine started.
my question is why the TestClosure can get the right answer but TestClsoure1 cant?
and if i change the way TestClosure start goroutine like below, TestClosure get wrong answer like TestClosure1, Why?
go func(){
v.printf()
}