Go by Example

Range over Channels

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

A channel passes values between goroutines, function calls started with go that can run while their caller continues. A for range loop over a channel receives each value until the channel is closed and its waiting values have been read. It waits when no value is ready.

The sender closes the channel after its final send. The receiver'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 the sender never closes the channel, the loop waits forever and its goroutine never finishes. Make it clear which part of the program closes the channel. Use a context, a value that carries a stop signal, when the receiver might need to stop early.

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