Essential Go range statement  Suggest an edit

range over a channel

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 elements sent over a channel.

Iteration ends when channel is closed.

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)
}
v: 3
v: 4
v: 5

  ↑ ↓ to navigate     ↵ to select     Esc to close