Go by Example

Select

Choose a ready channel operation from several cases, or wait until one can proceed.

A select chooses one ready send or receive operation from its cases. If none is ready, it waits unless there is a default case. If multiple cases are ready, Go chooses one without promising an order; it does not guarantee the case that became ready first will run.

Two goroutines send results independently. Each select receives one available value; if both sends are ready at once, either case can run first.

package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    first := make(chan string)
    second := make(chan string)
    go func() {
        time.Sleep(100 * time.Millisecond)
        first <- "first"
    }()
    go func() {
        time.Sleep(200 * time.Millisecond)
        second <- "second"
    }()
    for i := 0; i < 2; i++ {
        select {
        case value := <-first:
            fmt.Println(value)
        case value := <-second:
            fmt.Println(value)
        }
    }
}

In production

A select with a default case does not wait when no channel operation is ready. A nil channel is never ready, which can disable one case. Do not rely on a particular case being chosen when several are ready.

Enjoyed this? Get more software craft delivered to your inbox.