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;
4. fn main() {
5. let (tx, rx) = mpsc::channel();
7. tx.send(10).unwrap();
8. tx.send(20).unwrap();
10. println!("Received: {:?}", rx.recv());
11. println!("Received: {:?}", rx.recv());
13. let tx2 = tx.clone();
14. tx2.send(30).unwrap();
15. println!("Received: {:?}", rx.recv());
16. }
mpscstands for Multi-Producer, Single-Consumer.SenderandSyncSenderimplementClone(so you can make multiple producers) butReceiverdoes not.send()andrecv()returnResult. If they returnErr, it means the counterpartSenderorReceiveris dropped and the channel is closed.
