Essential Go Channels and select  Edit on GitHub      File Issue

Using range to read from a channel

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

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

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

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

The loop ends when the channel is closed.

This is a common pattern when using worker pool:

  ↑ ↓ to navigate     ↵ to select     Esc to close