Select
Go's select statement lets a goroutine wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.
Key Points
selectlets a goroutine wait on multiple channel operations.selectblocks until one of its cases can run.- If multiple cases are ready,
selectchooses one at random. - A
defaultcase can be used to preventselectfrom blocking. selectis often used to implement timeouts and cancellations.
Using Select
Here is an example of using select to wait on two channels.
package main
import (
"fmt"
"time"
)
func main() {
c1 := make(chan string)
c2 := make(chan string)
go func() {
time.Sleep(1 * time.Second)
c1 <- "one"
}()
go func() {
time.Sleep(2 * time.Second)
c2 <- "two"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
}received one
received twoSelect Statement Patterns
| Pattern | Example | Use Case |
|---|---|---|
| Multiple channels | select { case <-ch1: case <-ch2: } | Wait on multiple operations |
| Default case | select { case <-ch: default: } | Non-blocking receive |
| Timeout | case <-time.After(1 * time.Second): | Time-bounded operation |
| Done channel | case <-done: | Cancellation signal |
| Send on channel | case ch <- value: | Non-blocking send (with default) |