1
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 simple, using the unique.print()
will show on the screen the value of id
, but it doesn’t work properly. You’d be expected to return 1
, 3
and 5
, but he returns:
5
5
5
I can not understand why this does not work, because using in a "normal" way, without the use of goroutines, directly using valor.print()
it works.
It seems to me that this is something related to the use of goroutine, because this occurs?
Using:
teste := []*unique{&unique{1,2}, &unique{3,4}, &unique{5, 6}}
Seems to fix the problem, but I don’t know why.
Javascript has the same behavior, just by capturing the variable. As long as the rule is clear (and is), I don’t see anything special about it.
– navossoc