Create a channel with mpsc::channel, spawn a thread with the sender, and receive messages on the main thread using recv.
Use std::sync::mpsc::channel to create a sender and receiver, then pass the sender to a spawned thread to send messages back to the main thread.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = "hi";
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
Channels act like a pipe connecting two threads so they can pass data safely without sharing memory directly. One thread writes messages into the pipe, and the other thread reads them out, preventing crashes from conflicting access. Think of it like passing notes between two people in a room who cannot speak to each other.