Range over channels
Range over channels
For v := range ch receives values until the channel is closed and drained. Unlike ranging over a slice, the loop can wait for future values and yields one value per iteration, not an index-value pair.
package main
import ( "fmt")
func numbers() <-chan int { ch := make(chan int) go func() { defer close(ch) for i := 1; i <= 3; i++ { ch <- i } }() return ch}func main() { for v := range numbers() { fmt.Println(v * v) }}The producer defers close so the consumer can finish. Returning the channel before the sends finish allows concurrent consumption. Breaking early may leave the producer blocked; this example assumes full consumption. Cancellation is taught next.
Expected output:
149An empty stream
package main
import ( "fmt")
func main() { ch := make(chan int) close(ch) count := 0 for range ch { count++ } fmt.Println(count)}A closed empty channel yields zero iterations. An open empty channel waits, as does a nil channel. If the exact count is known, fixed-count receives may suffice without closing, but range needs closure to terminate normally.
Expected output:
0Try it locally
Produce 2,4,6,8 in a goroutine, close the channel, then sum with range in main.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Channels 06: Range over channels
Check the lesson objective before moving on.
When does range finish normally?
What risk arises when a consumer breaks early?