5

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

2
  • 2
    It's not a problem, it is how it behaves (it was designed to behave like that deliberately). Whether it's a "problem" for you in your particular case only you can say. Commented Dec 1, 2017 at 1:03
  • I should have said behavior instead of problem - I've edited it to make it clearer it's not a "problem", but my misunderstanding of the behavior. Commented Dec 1, 2017 at 5:13

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.