Go by Example

Range over Channels

Iterate over channel values until the channel is closed using a for-range loop.

A for-range loop over a channel receives values until the channel is closed and its buffered values have been received. The loop waits when no value is ready.

The producer closes the channel after its final send. The consumer's loop then ends automatically.

package main
 
import "fmt"
 
func produce(out chan<- int) {
    for i := 1; i <= 3; i++ {
        out <- i
    }
    close(out)
}
 
func main() {
    values := make(chan int)
    go produce(values)
    for value := range values {
        fmt.Println(value)
    }
}

In production

If a sender never closes the channel, the range loop can wait forever and keep its goroutine alive. Make channel ownership and shutdown explicit, or use context cancellation when a consumer may stop before the stream ends.

Enjoyed this? Get more software craft delivered to your inbox.