Select statements
… There can be at most one default case and it may appear anywhere in the list of cases.
As with a switch
statement, a select
statement may include either zero or one default
case.
The behavior of a select
statement is changed in important ways when a default
case is included. The details are coming soon, but I think this is a good chance to jump ahead a bit and elaborate.
Without a default
, case, a select statement blocks until either a send or receive operation succeeds:
select {
case <- recvA:
case <- recvB:
case sendA <- x:
}
fmt.Println("done!")
for as long as neither recvA
nor recvB
send data, and sendA
is incapable of being sent data (by virtue of being nil, or not having available capacity) done!
won’t print.
But if we add a default
case:
select {
case <- recvA:
case <- recvB:
case sendA <- x:
default:
fmt.Println("default")
}
fmt.Println("done!")
Now the select statement is going to finish very quickly. If none of the channels are able to receive/send, then the default
case triggers immediately, and we’ll see default
printed followed by done!
, immediately.
On the other hand, if, at the time the select statement is executed, one or more of the channels is available for sending or receiving, then of the available channels, one is selected, and its case executed.
More on how that’s all handled in the coming couple of days.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)