Match String Literals For Command Dispatch

Dispatch commands by matching string literal patterns, always ending with a catch-all arm since the compiler cannot prove str exhaustiveness.

RustCli Tooling

Code

rustsnippet
25 lines
fn dispatch(command: &str, amount: u32) -> String {
    // 字面量模式分发命令;&str 无法证明穷尽,必须提供兜底分支
    match command {
        "add" => format!("queue += {amount}"),
        "remove" => format!("queue -= {amount}"),
        "clear" => String::from("queue = 0"),
        other => format!("unknown command {other:?}"),
    }
}

fn main() {
    for (command, amount) in [("add", 5u32), ("remove", 2), ("clear", 0), ("flush", 9)] {
        println!("{command} -> {}", dispatch(command, amount));
    }

    // 字面量可以和范围模式混排在同一个 match 里
    for code in [200u16, 404, 503] {
        let label = match code {
            200..=299 => "success",
            404 => "missing",
            _ => "other",
        };
        println!("{code}: {label}");
    }
}

How it works

Count the functions dispatch and main as the entire surface area of Match String Literals For Command Dispatch.

Repetition is confined to for (command, amount) in [("add", 5u32), ("remove", 2), ("clear", 0), ("flush", 9)] — the rest of the file is straight-line. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Using it

The primary signature is fn dispatch(command: &str, amount: u32) -> String

The sequence dispatch lives in main; running the file triggers it.

Key statements

fn dispatch(command: &str, amount: u32) -> String {
// 字面量模式分发命令;&str 无法证明穷尽,必须提供兜底分支
match command {
"add" => format!("queue += {amount}"),
"remove" => format!("queue -= {amount}"),
"clear" => String::from("queue = 0"),
other => format!("unknown command {other:?}"),
}
}
let label = match code {
200..=299 => "success",
404 => "missing",
_ => "other",
};

Interactive Tools for This Topic

FAQ

How do you run Match String Literals For Command Dispatch?
The file is self-contained: run it directly, no dependencies to install beforehand.