Channels

Sharing data to the main thread from a spawned thread

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();
        tx.send(String::from("cool")).unwrap();
    });

    loop {
        match rx.recv() {
            Ok(message) => println!("Message from spawned thread: {}", message),
            _ => break,
        }
    }
}
Message from spawned thread: hi
Message from spawned thread: cool

This can be changed to run like an iterator instead


#![allow(unused)]
fn main() {
for received in rx {
	println!("Got: {}", received);
}
}