Middle
How does select work with multiple channels in Go?
sobes.tech AI
Answer from AI
In Go, the select statement is used to work with multiple channels simultaneously. It allows waiting until one of several channels becomes ready for an operation (reading or writing).
How it works:
selectblocks until at least one of the channels is ready.- When multiple channels are ready at the same time, one of them is chosen at random.
- You can specify a
defaultcase, which executes if no channels are ready, to avoid blocking.
Example:
select {
case msg := <-chan1:
fmt.Println("Received from chan1:", msg)
case chan2 <- 42:
fmt.Println("Sent to chan2")
default:
fmt.Println("No channel is ready")
}
Thus, select allows efficient management of multiple channels, implementing non-blocking or concurrent logic.