package main
import (
\"fmt\"
\"time\"
)
type field struct {
name string
}
func (p *field) print() {
fmt.Println(p.name)
}
func main() {
As stated above there’s a race condition it’s result depends on delays on different processes and not well defined and predictable.
For example if you add time.Sleep(1*time.Seconds)
you likely to get a correct result. Because usually goroutine prints faster than 1second and will have correct variable v
but it’s a very bad way.
Golang has a special race detector tool which helps to find such situations. I recommend read about it while reading testing
. Definitely it’s worth it.
There’s another way - explicitly pass variable value at goroutine start:
for _, v := range data {
go func(iv field) {
iv.print()
}(v)
}
Here v
will be copied to iv
(“internal v”) on every iteration and each goroutine will use correct value.