Select statements
…
- If the selected case is a
RecvStmt
with a short variable declaration or an assignment, the left-hand side expressions are evaluated and the received value (or values) are assigned.
This is to say that, given a select
case such as the following, where getAChannel()
returns a receiving channel:
case value, ok := <- getAChannel()
the right-hand side of the assignment operator (<- receiveChannel
) is evaluated earlier (back in step 1), and the left-hand side is only evaluated if the case is actually selected.
- The statement list of the selected case is executed.
The “statement list” refers to the code within the case code block. Pretty natural, eh? We only execute the code in the case if that case is selected.
Since communication on
nil
channels can never proceed, a select with onlynil
channels and no default case blocks forever.
We’ve already talked about nil
channels, so I don’t think I have much to add here. Let’s end our discussion of select statements with some sample code from the spec, that illustrates several select statements:
var a []int var c, c1, c2, c3, c4 chan int var i1, i2 int select { case i1 = <-c1: print("received ", i1, " from c1\n") case c2 <- i2: print("sent ", i2, " to c2\n") case i3, ok := (<-c3): // same as: i3, ok := <-c3 if ok { print("received ", i3, " from c3\n") } else { print("c3 is closed\n") } case a[f()] = <-c4: // same as: // case t := <-c4 // a[f()] = t default: print("no communication\n") } for { // send random sequence of bits to c select { case c <- 0: // note: no statement, no fallthrough, no folding of cases case c <- 1: } } select {} // block forever
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)