Middle
How does select work in Go? How to read from multiple channels simultaneously?
sobes.tech AI
Answer from AI
In Go, the select operator 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.
When you use select, Go blocks until one of the channels becomes available for an operation (read or write). Then, the corresponding block of code is executed.
Example of reading from multiple channels:
ch1 := make(chan int)
ch2 := make(chan int)
// Launch goroutines that send data
go func() { ch1 <- 1 }()
go func() { ch2 <- 2 }()
select {
case val := <-ch1:
fmt.Println("Received from ch1:", val)
case val := <-ch2:
fmt.Println("Received from ch2:", val)
case <-time.After(time.Second):
fmt.Println("Timeout")
}
In this example, select waits until data appears in one of the channels ch1 or ch2, or a timeout occurs. This allows efficient handling of multiple data sources simultaneously.