Middle
What is Select in Go used for?
sobes.tech AI
Answer from AI
In Go, the select operator is used to work with multiple channels simultaneously. It allows waiting for multiple read or write operations on channels and reacting to the one that becomes available first.
This is especially useful for implementing concurrent algorithms and handling multiple data sources without blocking.
Example of using select:
ch1 := make(chan int)
ch2 := make(chan int)
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 for data from ch1 or ch2 and outputs where the value came from, or it triggers a timeout.