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
- Each
casereceives from a different channel. - The first ready case runs; ties pick randomly.
time.Afterprovides a timeout arm.
Keywords and builtins used here
casechanforfuncreturnselectstring
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.
Step 1 of 3 in select, step 8 of 25 in Concurrency.