Select statements
…
- If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the “select” statement blocks until at least one of the communications can proceed.
Remember when I said last week that, unlike a switch
statement, select
does not execute from the top to bottom? Here’s where that’s spelled out for us.
If only a single communication can proceed, that case
executes.
If two or more can succeed at the time the select
is executed, then an arbitrary one is chosen, and executed.
Wait, but what if you want one channel to take priority over another? This is a legitimate desire sometimes. Then you might want to nest one or more select:
select {
case <- highPriorityChannel:
/* Do high priority things */
default:
select {
case <- lowPriorityChannel1:
/* Do low priority things */
case <- lowPriorityChannel1:
/* Do other low priority things */
default:
/* None of the channels were ready */
}
- Unless the selected case is the default case, the respective communication operation is executed.
Naturally, a default
case doesn’t have a communication operation, so it can’t be executed!
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)