What are Rust channels for message passing?
Answer
Rust follows the message-passing concurrency model with channels. The standard library provides std::sync::mpsc (multi-producer, single-consumer): let (tx, rx) = mpsc::channel();. Multiple senders can clone tx and send values; the single receiver calls rx.recv() (blocking) or rx.try_recv(). The channel is typed — only values of the specified type can be sent. For async code, Tokio provides tokio::sync::mpsc (multi-producer single-consumer), tokio::sync::broadcast (multi-producer multi-consumer, all receivers get every message), and tokio::sync::oneshot (sends exactly one value). Channels enforce the principle that data has a single owner: sending a value moves ownership into the channel, and the receiver takes ownership — preventing data races without locks.
Previous
What is the Tokio runtime and how is it used in Rust?
Next
How do you use thread::spawn in Rust?
More Rust Questions
View all →- Intermediate How does error handling with the ? operator work in Rust?
- Intermediate What are the thiserror and anyhow crates for error handling?
- Intermediate What are trait objects (dyn Trait) in Rust?
- Intermediate What are generics in Rust and how do where clauses work?
- Intermediate What are Rust smart pointers?