Go by Example: Select

The “select” statement is used to choose one out of multiple communication operations. The statement blocks until one of its communication operations can proceed, which then proceeds with the associated value. If multiple communication operations are ready, one is selected randomly.

package main

import "fmt"
import "time"

func main() {
    c1 := make(chan string)
    c2 := make(chan string)

    go func() {
        time.Sleep(time.Second * 1)
        c1 <- "one"
    }()
    go func() {
        time.Sleep(time.Second * 2)
        c2 <- "two"
    }()

    for i := 0; i < 2; i++ {
        select {
        case msg1 := <-c1:
            fmt.Println("received", msg1)
        case msg2 := <-c2:
            fmt.Println("received", msg2)
        }
    }
}

In this example, two goroutines are used to send values to two separate channels. The select statement blocks until either c1 or c2 has a value to receive. The example will print “received one” and then “received two”.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *