Channels

Rust channels have two parts: a Sender<T> and a Receiver<T>. The two parts are connected via the channel, but you only see the end-points.

  1. use std::sync::mpsc;
  2. use std::thread;
  3. fn main() {
  4. let (tx, rx) = mpsc::channel();
  5. tx.send(10).unwrap();
  6. tx.send(20).unwrap();
  7. println!("Received: {:?}", rx.recv());
  8. println!("Received: {:?}", rx.recv());
  9. let tx2 = tx.clone();
  10. tx2.send(30).unwrap();
  11. println!("Received: {:?}", rx.recv());
  12. }
  • mpsc stands for Multi-Producer, Single-Consumer. Sender and SyncSender implement Clone (so you can make multiple producers) but Receiver does not.
  • send() and recv() return Result. If they return Err, it means the counterpart Sender or Receiver is dropped and the channel is closed.