Select statement in Go
The select statement is used to wait for multiple channel operations to complete. It blocks until one of the channel operations is ready, and then executes that operation. If multiple operations are ready, one of them is chosen at random.
Here's an example of using the select statement:
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
ch1 <- 42
}()
go func() {
ch2 <- 24
}()
select {
case val := <-ch1:
fmt.Println("received from ch1:", val)
case val := <-ch2:
fmt.Println("received from ch2:", val)
}
In this example, we create two channels and two goroutines that send values over the channels. We then use the select statement to wait for either of the channels to receive a value, and print the received value.
The select statement is useful for building complex synchronization mechanisms that involve multiple channels.
No comments:
Post a Comment