Middle
What are channels in Go and the select operator?
sobes.tech AI
Answer from AI
In Go, channels are a mechanism for passing data between goroutines, providing synchronization and message exchange.
A channel is created using the make function and can be buffered or unbuffered (without a buffer). Values of a specific type can be sent and received through the channel.
The select statement allows waiting on multiple channel operations simultaneously and reacting to the one that becomes available first. This is useful for organizing concurrent behavior and timeouts.
Example:
ch1 := make(chan int)
ch2 := make(chan int)
// Launch a goroutine that sends data to ch1
go func() {
ch1 <- 1
}()
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")
}
Here, select waits for data from ch1 or ch2, or a timeout after 1 second.