Join me again today as I’ll be coding and answering questions on my livestream. Join me
Select statements
A “select” statement chooses which of a set of possible send or receive operations will proceed. It looks similar to a “switch” statement but with the cases all referring to communication operations.
SelectStmt = "select" "{" { CommClause } "}" . CommClause = CommCase ":" StatementList . CommCase = "case" ( SendStmt | RecvStmt ) | "default" . RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr . RecvExpr = Expression .
So a switch statement may contain send cases, receive cases, or up to a single default
. But we start with some details on receive cases, as they have the most variability.
A case with a RecvStmt may assign the result of a RecvExpr to one or two variables, which may be declared using a short variable declaration. The RecvExpr must be a (possibly parenthesized) receive operation.
As when receiving data from a channel outside of a switch statement, you may assign the received value to zero, one, or two variables.
value, ok := <- recvCh
is equivalent to:
case value, ok := <- recvCh
Also the same, you may omit the optional second boolean variable:
case value := <- recvCh
Or all of the varaibles entirely, in which case the value received is simply discarded:
case <- recvCh
And finally, as with receive operations, the receive expression may be parenthesized, which is sometimes necessary to avoid ambiguity.
case value, ok := (<-ch1)
case value := (<-ch2)
case (<-ch3)
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)