Select
Choose a ready channel operation from several cases, or wait until one can proceed.
select waits until it can send or receive on one of its listed channels. A channel passes values between goroutines; a goroutine is a function call started with go that can run while its caller continues. If no operation can proceed, select waits unless there is a default case. If several can proceed, Go chooses one without promising an order.
The two goroutines send results on channels. Each select receives one value; if both are ready, 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.