golang

Golang Select Call

The Golang select call refers to a switch statement used in channel communication. It allows you to wait on multiple channel operations, such as to send or receive.

There is nothing complex about the select calls in Go.

The syntax is similar to a switch statement as:

select {
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.

package main
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:

package main
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list