There is nothing complex about the select calls in Go.
The syntax is similar to a switch statement as:
case ChannelOperation:
//
case ChannelOperation2:
//
case ChanneOperation3:
//
default:
// default case
}
Golang Select
Consider the following code example that illustrates how to use the Go select call.
import "fmt"
func main() {
channel1 := make(chan string)
channel2 := make(chan string)
go func() {
channel1 <- "channel 1"
}()
go func() {
channel2 <- "channel 2"
}()
select {
case msg11 := <-channel1:
fmt.Println("Message recieved from: ", msg11)
case msg2 := <-channel2:
fmt.Println("Message recieved from: ", msg2)
}
}
If we run the previous code, you notice we get a different output on every run. The select statement chooses any output if all the cases are ready.
We can select a default case using the default keyword to prevent the select call from blocking the main goroutine.
An example is as shown:
import "fmt"
func main() {
channel1 := make(chan string)
channel2 := make(chan string)
go func() {
channel1 <- "channel 1"
}()
go func() {
channel2 <- "channel 2"
}()
select {
case msg11 := <-channel1:
fmt.Println("Message recieved from: ", msg11)
case msg2 := <-channel2:
fmt.Println("Message recieved from: ", msg2)
default:
fmt.Println("Goroutines are not ready!")
}
}
The previous program will run the default case since the goroutines are ready and have returned no output.
Conclusion
We can use the Go select call to selectively fetch data from several channels. The select call will randomly select the data if all the providers are ready. If none are ready, we execute the default case. We hope you found this article. Check out other Linux Hint articles for more tips and information.