Non-blocking receive with select

suggest change

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.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents