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

Taught in

References