The select keyword
The select
keyword is really important because it allows you 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. Lastly, 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 you the power to listen to multiple channels using a single select block. Consequently, you can have non-blocking operations on channels, provided that you have implemented your 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...