Essential Go Channels and select  Edit on GitHub      File Issue

Non-blocking receive with select

You can use default part of select statement to do a non-blocking wait.

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

	for {
		select {
		case n := <-ch:
			fmt.Printf("Received %d from a channel\n", n)
			break end
			fmt.Print("Channel is empty\n")
			ch <- 8
		// wait for channel to be filled with values
		// don't use time.Sleep() like that in production code
		time.Sleep(20 * time.Millisecond)
Channel is empty
Received 8 from a channel

During first iteration of for loop select immediately ends up in default clause because channel is empty.

We send a value to the channel there so the next select will pick up the value from the channel.

  ↑ ↓ to navigate     ↵ to select     Esc to close