The select Keyword
Let’s learn about the select keyword in Go.
We'll cover the following
Importance of the select
keyword
The select
keyword is really important because it allows us to listen to multiple channels at the same time. A select
block can have multiple cases and an optional default
case, which mimics the switch
statement. It is good for select
blocks to have a timeout option just in case. Last, a select
without any cases (select{}
) waits forever.
In practice, this means that select
allows a goroutine to wait on multiple communication operations. So, select
gives us the power to listen to multiple channels using a single select
block. As a consequence, we can have nonblocking operations on channels, provided that we have implemented our select
blocks appropriately.
A select
statement is not evaluated sequentially, as all of its channels are examined simultaneously. If none of the channels in a select statement are ready, the select
statement blocks (waits) until one of the channels is ready. If multiple channels of a select
statement are ready, then the Go runtime makes a random selection from the set of these ready channels.
Coding example
The code in select.go
presents a simple use of select
running in a goroutine that has three cases. But first, let’s see how the goroutine that contains select
runs:
Get hands-on with 1400+ tech skills courses.