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.
Code
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
Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- How do you run Match String Literals For Command Dispatch?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.