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 when the channel is closed.

This is a common pattern when using worker pool: * create a single channel for all workers * launch workers * workers use for v := range chan to pick up jobs to process * after enquing all jobs, close the channel so that worker goroutines end when they process all jobs from a channel

Feedback about page:

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



Table Of Contents