How to Use Channels (mpsc) for Thread Communication in Rust

Create an mpsc channel in Rust to send data from a spawned thread to the main thread using tx.send and rx.recv.

Use std::sync::mpsc::channel() to create a sender and receiver, spawn a thread with move to send data, and call recv() in the main thread to receive it.

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });

    let received = rx.recv().unwrap();
    println!("Got: {received}");
}