Goroutine channel as parameter?

I just read THIS topic and I didn’t understand the subject that was touched on, and couldn’t find satisfying information. (And since I didn’t want to divert that topic, I created a new one)

As far as I understood, you objected to referencing the channel directly in the anonymous function; it should rather be passed in as a parameter. I.e.:
https://play.golang.org/p/BzgFVXztBn (“bad”)
https://play.golang.org/p/FZH3YTLTkU (“good”)

Now I don’t fully understand what’s wrong with that. I see the typical problems with using variables this way,
i.e. I see a potential for memory leakage (the goroutines are referencing a variable in the calling function), corruption (changing the queue would change it for all goroutines)…
But I don’t see anything wrong with this pattern in general, it should be safe as long as you keep the caveats in mind, shouldn’t it? After all, chan variables are just reference structs, similar to slices and maps?

I would appreciate if you were so kind to elaborate :slight_smile:

There is nothing wrong with using a channel in a closure, like in your “bad” example.

The thread you’re referring to is a little confusing as the question is based on a misunderstanding, the first reply is incorrect, and then there is confusion about what the question is really about. :slight_smile:

1 Like

Oh, ok thanks.
I saw the confusion about the question, but I thought it was about whether using it would produce race conditions as opposed to using the channel in a closure.
Thanks for clarifying :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.