0
0
Rustprogramming~5 mins

Message passing concepts in Rust

Choose your learning style9 modes available
Introduction

Message passing helps different parts of a program talk to each other safely without mixing up data.

When you want to send data between different parts of a program running at the same time.
When you want to avoid mistakes caused by sharing data directly.
When you want to organize your program so parts work independently but still communicate.
When you build programs that do many things at once, like a chat app or a game.
When you want to keep your program safe from crashes caused by data conflicts.
Syntax
Rust
use std::sync::mpsc;

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

    // tx is the sender
    // rx is the receiver

    // Send a message
    let _ = tx.send("Hello");

    // Receive a message
    let message = rx.recv().unwrap();
}

mpsc stands for multiple producer, single consumer.

You create a channel with mpsc::channel() which gives you a sender and a receiver.

Examples
Send and receive a number using the channel.
Rust
use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();
    tx.send(5).unwrap();
    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}
Send a message from a new thread to the main thread.
Rust
use std::sync::mpsc;
use std::thread;

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

    thread::spawn(move || {
        tx.send("Hi from thread").unwrap();
    });

    let message = rx.recv().unwrap();
    println!("Message: {}", message);
}
You can clone the sender to have multiple senders.
Rust
use std::sync::mpsc;

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

    let tx2 = tx.clone();

    // Now two senders can send messages
}
Sample Program

This program creates a channel and a new thread. The thread sends three messages one by one. The main thread receives and prints each message.

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

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

    thread::spawn(move || {
        let messages = vec!["Hello", "from", "thread"];
        for msg in messages {
            tx.send(msg).unwrap();
        }
    });

    for received in rx {
        println!("Got: {}", received);
    }
}
OutputSuccess
Important Notes

Sending messages moves ownership, so data is safely transferred.

Receiving blocks the program until a message arrives.

Cloning the sender lets many parts send messages to one receiver.

Summary

Message passing lets parts of a program send data safely without sharing memory.

Use mpsc::channel() to create a sender and receiver.

Senders use send(), receivers use recv() to get messages.