Sobes.tech
Principal

Select operator in Go — features of working with multiple channels

sobes.tech AI

Answer from AI

The select operator in Go allows working with multiple channels simultaneously, waiting for one of them to be ready for reading or writing. It blocks until one of the channels becomes available, then executes the corresponding case.

Features of working with multiple channels:

  • If multiple channels are ready at the same time, a random case is chosen, which helps avoid deadlocks and ensures fairness.
  • You can use the default case, which executes if no channels are ready, to avoid blocking.
  • select is often used for timeouts and canceling operations via channels.

Example:

select {
case msg := <-chan1:
    fmt.Println("Received from chan1:", msg)
case chan2 <- 42:
    fmt.Println("Sent to chan2")
case <-time.After(time.Second * 5):
    fmt.Println("Timeout after 5 seconds")
default:
    fmt.Println("No channel is ready")
}

Thus, select allows efficient management of concurrent operations with channels.