Using range to read from a channel

suggest change

When reading multiple values from a channel, using range is a common pattern:

func foo(ch chan int) {
	ch <- 1
	ch <- 2
	close(ch)
}

func main() {
	ch := make(chan int)
	go foo(ch)
	for n := range ch {
		fmt.Println(n)
	}
	fmt.Println("channel is now closed")
}
1
2
channel is now closed

Using a for range loop is one of three ways to read values from a channel.

The loop ends after the channel is closed and the remaining values have been received. If the channel is never closed, the loop waits forever.

This is a common worker-pool pattern:

Feedback about page:

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



Table Of Contents