Iterating over a channel with range
:
https://codeeval.dev/gist/1e6322bb7dc0aad39f8c8a01e6c19651
range
over a channel receives elements sent over a channel.
Iteration ends when channel is closed.
This is a more convenient version of:
// :glo
package main
import "fmt"
func fillAndCloseChannel(ch chan int) {
for i := 0; i < 3; i++ {
ch <- i + 3
}
close(ch)
}
func main() {
// :show start
ch := make(chan int)
go fillAndCloseChannel(ch)
for {
v, ok := <-ch
if !ok {
break
}
fmt.Printf("v: %d\\n", v)
}
// :show end
}