Home > Article > Backend Development > How Does Go\'s `select` Statement Handle Simultaneous Receive and Send Operations?
Communicating Channels through Select Statements
To forward results between channels, you may encounter code like this:
for { select { ... case ch2 <- <-ch1: ... } }
This design raises questions about how select operates on both receive and send operations.
Receive or Send, or Both?
Contrary to selecting either operation individually, the select statement evaluates the entire operation, including both receive (<-ch1) and send (ch2 <-) operations, upon entering the select. This means that:
case ch2 <- <-ch1:
will immediately block on receiving from ch1, and then the select will determine whether the send on ch2 proceeds or a different case is chosen.
In essence, the select treats the above case as:
case ch2 <- <something>:
where
Side Effects
This design carries a side effect: if the case with the nested receive (<-ch1) is not selected, the value from ch1 is still consumed and discarded.
The above is the detailed content of How Does Go\'s `select` Statement Handle Simultaneous Receive and Send Operations?. For more information, please follow other related articles on the PHP Chinese website!