select statement
A Go statement that waits on several channel operations at once and runs the first one that is ready.
In more detail
If several are ready, one is picked at random, so never rely on case order. A default case runs immediately when nothing is ready, making the select non-blocking. Adding a case on time.After or ctx.Done() gives the wait a timeout or a way to cancel.
Example
select {
case value := <-result:
fmt.Println(value)
case <-time.After(time.Second):
fmt.Println("timeout")
}Related terms
- channel — A typed pipe in Go that one goroutine sends values into and another receives them from, safely handing data between them.
- timer and ticker — Go time values that deliver on a channel later: a timer fires once after a duration, a ticker fires repeatedly at an interval.
- context cancellation — Telling every function using a context to stop, by calling the cancel function returned when the context was created.
- blocking operation — An operation that makes the code wait until something happens, such as a receive waiting for a value to arrive on a channel.
- polling — Having the client ask repeatedly, on its own schedule, whether something has changed or finished.
Taught in
- The select Statement — Concurrent Systems Programming with Go
- The context Package — Concurrent Systems Programming with Go
- Context Cancellation and Timeouts — Concurrent Systems Programming with Go