A Sender is the transmitting handle for a Rust standard-library channel. The matching Receiver accepts values of the same type, so a channel connects one or more senders to one receiver. Create both with std::sync::mpsc::channel(), usually by destructuring its returned tuple. section 12.5.1 section 12.5
Important Sender behaviors include:
- send(value) transmits a value and returns a Result, so unwrap() can expose failures in a small example while real programs should handle errors deliberately. section 12.5.2
- Clone a Sender when several threads or producers need to send through the same channel. section 12.5.2
- Dropping the Receiver makes send fail because the channel is closed. Dropping every Sender eventually lets recv return an error after queued values are consumed. section 12.5.2
- The compiler can infer the transmitted type after a value is sent; otherwise, annotate the channel as Sender<T> and Receiver<T>. section 12.5.1
Send a value
use std::sync::mpsc::channel; fn main() { let (sender, receiver) = channel(); sender.send(5).unwrap(); println!("{}", receiver.recv().unwrap()); } Here, sending 5 supplies the type as i32. recv() waits for the value, and the program prints 5. If the receiver is dropped first, send returns an error instead. section 12.5.2
use std::sync::mpsc::channel;
fn main() {
let (sender, receiver) = channel();
let sender_clone = sender.clone();
std::thread::spawn(move || {
sender.send("Send a &str this time").unwrap(); #1
sender.send("Send a &str this time").unwrap(); #1
});
std::thread::spawn(move || {
sender_clone.send("And here is another &str").unwrap(); #2
sender_clone.send("And here is another &str").unwrap(); #2
});
while let Ok(res) = receiver.recv() {
println!("{res}");
}
}
Inspect a focused example with cloned senders running in separate threads and sending several string slices to one receiver. section 12.5.2
