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.

use std::sync::mpsc;

fn main() {
    // We'll iterate over 2 values in the `sender` channel.
    let (sender, receiver) = mpsc::channel();
    
    sender.send("one".to_string()).unwrap();
    sender.send("two".to_string()).unwrap();
    drop(sender); // Close the channel

    // This `for` loop iterates over each element as it's
    // received from `receiver`. Because we dropped the sender
    // above, the iteration terminates after receiving the 2 elements.
    for elem in receiver {
        println!("{}", elem);
    }
}

When you run this program, you’ll see:

one
two

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.