Card 1 / 6
Push every item through a channel, then drain the receiver into a Vec (in send order).
items |
result |
|---|---|
vec![1, 2, 3] |
[1, 2, 3] |
vec![] |
[] |
vec![42] |
[42] |
mpsc::channel() returns the pair (Sender<T>, Receiver<T>). tx.send(x) queues a value and the receiver yields values back in send order.
The receiver's iterator ends only when the last sender is dropped. Nothing else holds one here, so drop(tx) before rx.iter().collect() — otherwise it blocks forever waiting on a message that will never come.
/// Create a channel, send every value from `items` through it, then collect
/// everything the receiver yields into a Vec (in send order).
fn round_trip(items: Vec<i32>) -> Vec<i32> {
let (tx, rx) = mpsc::channel();
for x in items {
tx.send(x).unwrap();
}
drop(tx);
rx.iter().collect()
}Card 2 / 6
Have a worker thread stream the numbers 1..=n over a channel; multiply them on the main thread.