Data can also be exchanged between threads by passing messages among them. This is implemented in Rust by channels, which are like unidirectional pipes that connect two threads; data is processed first-in, first-out.
Data flows over this channel between two endpoints: from the Sender<T> to the Receiver<T>, both of which are generic and take the type T of the message to be transferred (which obviously must be the same for the Sender and Receiver). In this mechanism, a copy of the data to share is made for the receiving thread, so you wouldn't want to use this for very large data:

To create a channel, we need to import the mpsc submodule from std::sync (mpsc, which stands for multi-producer, single-consumer communication primitives, and then use the channel() method:
// code from Chapter 9/code/channels.rs: use std::thread; use std::sync::mpsc::channel;use std::sync::mpsc::{Sender, Receiver}; fn main() { let (tx, rx): (Sender<i32>, Receiver<i32>) = channel(); }
This creates a tuple of endpoints, tx (t stands for transmission) being the Sender and rx (r stands for receiver) being the Receiver. We have indicated that we will send i32 integers over the channel, but the type annotations are not needed if the compiler can deduce the channel datatype from the rest of the code.