std-method

Receiver::iter: receive until disconnection

The borrowed iterator waits for messages and ends after the queue is empty and all senders have gone away. Keep no unused sending handles alive when draining to completion. Expected stdout (not executed): [1, 3, 5] Common mistake: Collecting a receiver iterator while an idle sender remains alive.

Formal Syntax & Structure

rust syntaxrust
receiver.iter() -> Iter<'_, T>

Working Example

Example Snippetrust
fn main() {    use std::sync::mpsc;    let (tx, rx) = mpsc::channel();    for n in [1, 3, 5] { tx.send(n).unwrap(); }    drop(tx);    let values: Vec<_> = rx.iter().collect();    println!("{:?}", values);}
Rust Reference