Essential Go Channels and select  Suggest an edit

Timeout reading from channel with select

Receiving from a channel with <- chan or for range loop blocks.

Sometimes you want to limit time waiting for a value on a channel.

It’s possible with select:

func main() {
	chResult := make(chan int, 1)

	go func() {
		time.Sleep(1 * time.Second)
		chResult <- 5
		fmt.Printf("Worker finished")

	select {
	case res := <-chResult:
		fmt.Printf("Got %d from worker\n", res)
	case <-time.After(100 * time.Millisecond):
		fmt.Printf("Timed out before worker finished\n")
Timed out before worker finished
  ↑ ↓ to navigate     ↵ to select     Esc to close