Why does Go uses channels to send and receive data between goroutines instead of using normal variables?

Issue

I could not find anything about this question except this explanation by Wikipedia https://en.wikipedia.org/wiki/Channel_(programming). But I’m not satisfied with the explanation.

What problem do channels solve?
Why don’t we just use normal variables to send and receive data instead?

Solution

If by "normal variables" you mean, for example, a slice that multiple goroutines write to and read from, then this is a guaranteed way to get data races (you don’t want to get data races). You can avoid concurrent access by using some kind of synchronization (such as Mutex or RWLock).

At this point, you

  1. reinvented channels (which are basically that, a slice under a mutex)
  2. spent more time than you needed to and still your solution is inferior (there’s no syntax support, you can’t use your slices in select, etc.)

Answered By – Sergio Tulentsev

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.