Chapter 12

Communicating between Goroutines Using Channels

IN THIS CHAPTER

Bullet Working with channels

Bullet Using for-range loops on channels

Bullet Using the select statement on channels

Bullet 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 ...

Get Go Programming Language For Dummies now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.