Range Over Channels in Rust
In a previous example, we saw how for
and loop
provide iteration over basic data structures. We can also use this syntax to iterate over values received from a channel.
When you run this program, you’ll see:
This example also showed that it’s possible to close a non-empty channel but still have the remaining values be received. In Rust, this is done by dropping the sender, which closes the channel.
In Rust, we use the mpsc::channel()
function to create a multiple producer, single consumer channel. The send
method is used to send values into the channel, and the for
loop automatically receives values until the channel is closed.
Note that unlike in some other languages, Rust’s channels are not buffered by default. If you need a buffered channel, you can use mpsc::sync_channel(n)
where n
is the buffer size.