RRust By Example
intermediateConcurrency

Channel Basic

Send messages between threads with channels.

Channel Basic

Send messages between threads with channels.

Difficulty

Intermediate

Code

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

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

    thread::spawn(move || {
        let messages = vec!["hello", "from", "the", "thread"];
        for msg in messages {
            tx.send(msg).unwrap();
            thread::sleep(std::time::Duration::from_millis(10));
        }
    });

    for received in rx {
        println!("got: {}", received);
    }
}

Explanation

This example demonstrates how to use channel basic in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the concurrency category to build a complete understanding of this topic.

More Concurrency Examples