Select Statement in Go Language
The select
statement is a powerful feature in Go that allows you to work with multiple channels concurrently. It enables you to wait for multiple channel operations and choose the first one that becomes ready. It’s often used in scenarios where you need to coordinate communication between different goroutines using channels.
Here’s the syntax of the select
statement:
select {
case <-channel1:
// Do something when channel1 is ready
case data := <-channel2:
// Do something with data from channel2
case channel3 <- value:
// Send value to channel3
default:
// Do something when no channel operation is ready
}
Key points to understand about the select
statement:
- The
select
statement lets you wait for multiple channel operations simultaneously. - If multiple channels are ready, one of them is chosen at random.
- The
<-
operator is used to receive data from a channel, andchannel <- value
is used to send data to a channel. - The
default
case is executed when no other channel operation is ready. - The
select
statement is non-blocking; it only blocks if all channels are unbuffered and none of them are ready.
Here’s a simple example of using the select
statement:
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
time.Sleep(time.Second)
ch1 <- 42
}()
go func() {
time.Sleep(2 * time.Second)
ch2 <- 99
}()
select {
case data := <-ch1:
fmt.Println("Received from ch1:", data)
case data := <-ch2:
fmt.Println("Received from ch2:", data)
case <-time.After(3 * time.Second):
fmt.Println("Timeout")
}
}
Output (may vary due to random selection):
Received from ch1: 42
In this example, two goroutines send data to two different channels after different time intervals. The select
statement waits for the first channel to become ready. Since the channel associated with the first goroutine is ready before the other, the <-ch1
case is executed.
The select
statement is a fundamental tool for coordinating communication between goroutines efficiently, enabling you to create powerful and responsive concurrent programs.