Working with multiple channels using the select statement
You can only send data or receive data from a channel at any given time. If you are interacting with multiple goroutines (and thus, multiple concurrent events), you need a language construct that will let you interact with multiple channels at once. That construct is the select
statement.
This section shows how select
is used.
How to do it...
A blocking select
statement chooses an active case from zero or more cases. Each case is a channel send or channel receive event. If there are no active cases (that is, none of the channels can be sent to or received from), select
is blocked.
In the following example, the select
statement waits to receive from one of two channels. The program receives from only one of the channels. If both channels are ready, one of the channels will be picked randomly. The other channel will be left unread:
ch1:=make(chan int) ch2:=make(chan int) go func() { ch1<-1 }() go...