Enum Messages Matched Over Channels

An enum over an mpsc channel carries typed commands; the worker matches Add, Greet, and Stop arms, and recv returning Err ends the loop naturally.

RustResilience

Code

rustsnippet
35 lines
use std::sync::mpsc::{channel, Receiver};
use std::thread;

// 一个枚举承载 worker 可收到的全部命令,match 逐分支分派
enum Command {
    Add { lhs: i64, rhs: i64 },
    Greet(String),
    Stop,
}

fn worker(receiver: Receiver<Command>) -> thread::JoinHandle<()> {
    thread::spawn(move || {
        // 通道关闭后 recv 返回 Err,循环自然结束
        while let Ok(msg) = receiver.recv() {
            match msg {
                Command::Add { lhs, rhs } => println!("sum: {}", lhs + rhs),
                Command::Greet(name) => println!("hello, {name}"),
                Command::Stop => break,
            }
        }
        println!("worker drained");
    })
}

fn main() {
    let (tx, rx) = channel::<Command>();
    let handle = worker(rx);

    tx.send(Command::Add { lhs: 19, rhs: 23 }).unwrap();
    tx.send(Command::Greet("ada".into())).unwrap();
    tx.send(Command::Stop).unwrap();
    drop(tx);

    handle.join().unwrap();
}

How it works

Enum Messages Matched Over Channels is built around the functions worker and main.

The file repeats itself only inside while let Ok(msg) = receiver.recv(). A match spells out every case; omit one and the code does not compile.

What to watch for

  • Every symbol it touches is a language built-in — nothing to fetch.

Putting it to use

The definition reads fn worker(receiver: Receiver<Command>) -> thread::JoinHandle<()>

Output lines are prefixed (sum:, hello,, worker drained), making each step’s effect easy to spot.

main sequences worker; executing the file runs that flow once.

Core lines

while let Ok(msg) = receiver.recv() {
    match msg {
        Command::Add { lhs, rhs } => println!("sum: {}", lhs + rhs),
        Command::Greet(name) => println!("hello, {name}"),
        Command::Stop => break,
    }
}
tx.send(Command::Add { lhs: 19, rhs: 23 }).unwrap();
tx.send(Command::Greet("ada".into())).unwrap();

Interactive Tools for This Topic

FAQ

What does Enum Messages Matched Over Channels print when run?
No setup needed: run the file and look for labeled lines like `sum:`, `hello,`, `worker drained` in the output.