typestar

select in Go

Waiting on whichever channel is ready first.

func race(fast, slow <-chan string) {
    for i := 0; i < 2; i++ {
        select {
        case msg := <-fast:
            fmt.Println("fast:", msg)
        case msg := <-slow:
            fmt.Println("slow:", msg)
        case <-time.After(time.Second):
            fmt.Println("timed out")
            return
        }
    }
}

How it works

  1. Each case receives from a different channel.
  2. The first ready case runs; ties pick randomly.
  3. time.After provides a timeout arm.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
233
Tokens
74
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 44 seconds.

Type this snippet

Step 1 of 3 in select, step 8 of 25 in Concurrency.

← Previous Next →

select in other languages