Using range to read from a channel
suggest changeWhen reading multiple values from a channel, using range is a common pattern:
func foo(ch chan int) {
ch <- 1
ch <- 2
close(ch)
}
func main() {
ch := make(chan int)
go foo(ch)
for n := range ch {
fmt.Println(n)
}
fmt.Println("channel is now closed")
}
1
2
channel is now closed
Using a for range loop is one of three ways to read values from a 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 common worker-pool pattern:
- create one channel for all workers
- launch the workers
- workers use
for v := range jobsto take jobs - after enqueuing every job, close the channel so each worker finishes after it has processed the remaining jobs
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents