Select in Go

Go: Select

In Go, the "select" statement is a powerful tool for working with channels.

Select allows us to wait for multiple channels to become available for sending or receiving, and then perform the appropriate action based on which channel is ready.

How to use the "select" statement in Go:

    func main() {
        ch1 := make(chan int)
        ch2 := make(chan string)

        go func() {
            ch1 <- 42
        }()

        go func() {
            ch2 <- "hello"
        }()

        select {
        case x := <-ch1:
            fmt.Println("received", x)
        case s := <-ch2:
            fmt.Println("received", s)
        }
    }

Send values on multiple channels using select in Go

The "select" statement can also be used to send values on multiple channels at once. Check below example:

    func main() {
        ch1 := make(chan int)
        ch2 := make(chan string)

        go func() {
            ch1 <- 42
        }()

        go func() {
            ch2 <- "hello"
        }()

        select {
        case ch1 <- 100:
            fmt.Println("sent 100 on ch1")
        case ch2 <- "world":
            fmt.Println("sent 'world' on ch2")
        }
    }

In above example, we used the "select" statement to try to send a value on both channels at once. Whichever channel is ready to receive the value first will be used to send the value.

Select allows us to write efficient and flexible concurrent programs.

Previous Article

Next Article