Chapter 12
Communicating between Goroutines Using Channels
IN THIS CHAPTER
Working with channels
Using for-range loops on channels
Using the select statement on channels
Working with unbuffered channels
In Chapter 11, I introduce you to goroutines, one of the key features of the Go programming language. Goroutines are executed independently of one another and are a great way to implement concurrent programming. However, very often, goroutines need a way to communicate with each other in order to work properly. In Go, you can get goroutines to communicate with one another through pipes known as channels. In this chapter, I show you how channel works.
Understanding Channels
In Go, channels are the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values in another goroutine. Think of channels as temporary storage for passing values between goroutines.
To create a channel, you use the make() function, together with the chan keyword and the type of data that you want the channel to store for you, like this:
ch := make(chan ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access