This loop is always repeating the last value, consider the following:
type unique struct {
id, nonce uint64
}
func (unique *unique) print() {
fmt.Println(unique.id)
}
func main() {
teste := []unique{unique{1, 2}, unique{3, 4}, unique{5, 6}}
for _, valor := range teste {
go valor.print()
}
time.Sleep(4 * time.Second)
}
It's pretty simplistic, using unique.print()
will display the id
on the screen, however this does not work correctly. It would be expected to return 1
, 3
and 5
, but it returns:
5
5
5
I can not understand why this does not work, because using "normal" without using goroutines , directly using valor.print()
it works .
I think this is something related to the use of goroutine , why does this occur?
Using:
teste := []*unique{&unique{1,2}, &unique{3,4}, &unique{5, 6}}
It seems to fix the problem, but I do not know why.