Sobes.tech
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:

  • select blocks 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 default case, 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.

How does select work with multiple channels in Go… - sobes.tech