Senders and Receivers

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

  1. use std::sync::mpsc;
  2. fn main() {
  3.     let (tx, rx) = mpsc::channel();
  4.     tx.send(10).unwrap();
  5.     tx.send(20).unwrap();
  6.     println!("Received: {:?}", rx.recv());
  7.     println!("Received: {:?}", rx.recv());
  8.     let tx2 = tx.clone();
  9.     tx2.send(30).unwrap();
  10.     println!("Received: {:?}", rx.recv());
  11. }

This slide should take about 9 minutes.

  • 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.