Senior
What is the practical use of the keyword select?
sobes.tech AI
Answer from AI
In Go, the keyword select is used for working with multiple channels simultaneously. It allows waiting for read or write operations on multiple channels and reacting to the one that is ready first. This is useful for implementing non-blocking channel operations, timeouts, multiplexing, and handling multiple data sources.
Example usage:
select {
case msg := <-ch1:
fmt.Println("Received from ch1:", msg)
case ch2 <- 42:
fmt.Println("Sent to ch2")
case <-time.After(time.Second):
fmt.Println("Timeout")
}
Here, select waits until either a message arrives from ch1, or it can send a value to ch2, or a timeout of 1 second occurs.