In a
previous
example we saw how
for
and
range
provide iteration over basic data structures.
We can also use this syntax to iterate over
values received from a channel.
This
range
iterates over each element as it’s
received from
queue
. Because we
close
d the
channel above, the iteration terminates after
receiving the 2 elements.
forelem:=rangequeue{fmt.Println(elem)}}
$ go run range-over-channels.go
one
two
This example also showed that it’s possible to close
a non-empty channel but still have the remaining
values be received.