range over a channel

suggest change

Iterating over a channel with range:

func fillAndCloseChannel(ch chan int) {
	for i := 0; i < 3; i++ {
		ch <- i + 3
	}
	close(ch)
}

	ch := make(chan int)
	go fillAndCloseChannel(ch)

	for v := range ch {
		fmt.Printf("v: %d\n", v)
	}
v: 3
v: 4
v: 5

range over a channel receives values sent on the 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 more convenient version of:

	ch := make(chan int)
	go fillAndCloseChannel(ch)

	for {
		v, ok := <-ch
		if !ok {
			break
		}
		fmt.Printf("v: %d\n", v)
	}

Feedback about page:

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



Table Of Contents