I was reading that goroutines on loop iterators often result in the last value in the loop assignment being used for every iteration. E.g. https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables
However, does this only happen for closures, e.g. with anonymous functions?
I can't seem to reproduce the issue with this example https://play.golang.org/p/lpZ-yD1mHu
When I use an anonymous function like this, it recreates the issue https://play.golang.org/p/mDa0Z6mUP8
However, is this only a problem for closures, e.g. with anonymous functions?
Yes. The difference between
go speak(c)
and
go func() {
speak(c)
}()
is, the former calls speak
with the value of c
in a new goroutine. In the latter one, however, the anonymous function captures not the value of c
but the variable c
itself (by reference¹) and, at some later point in time, calls speak
with whatever value c
has at this point in time.
¹: There are no "references" in golang, I'm not sure how this is exactly implemented, but it is as if they reference the original variable.