Bind Subpatterns With @ In Match
Capture the matched value with @ while range and or-patterns still select the branch, so one binding serves both branch decisions and output formatting.
Code
fn classify(n: u32) -> String {
match n {
0 => "zero".to_string(),
// @ 绑定(bind)整个匹配值,同时范围子模式(subpattern)继续选分支
n @ 1..=12 => format!("small: {n}"),
n @ 13..=99 => format!("medium: {n}"),
_ => format!("large: {n}"),
}
}
fn dispatch(cmd: &str) -> String {
match cmd {
// @ 也适用于 or-pattern:绑定命中值,分支里直接复用
c @ ("start" | "restart") => format!("launching via {c}"),
"stop" => "stopping".to_string(),
other => format!("unknown command {other}"),
}
}
fn main() {
for n in [0, 7, 42, 500] {
println!("{n} -> {}", classify(n));
}
for cmd in ["start", "restart", "stop", "pause"] {
println!("{cmd} -> {}", dispatch(cmd));
}
}How it works
Bind Subpatterns With @ In Match is built around the functions classify, dispatch and main.
Repetition is confined to for n in [0, 7, 42, 500] — the rest of the file is straight-line. The match expression is exhaustive — the compiler enforces that no case is missing.
Applying it
Entry signature: fn classify(n: u32) -> String
The demo flow inside main is classify and dispatch — run the file to see it end to end.
Statements that matter
fn dispatch(cmd: &str) -> String {
match cmd {
// @ 也适用于 or-pattern:绑定命中值,分支里直接复用
c @ ("start" | "restart") => format!("launching via {c}"),
"stop" => "stopping".to_string(),
other => format!("unknown command {other}"),
}
}
fn classify(n: u32) -> String {
match n {
0 => "zero".to_string(),
// @ 绑定(bind)整个匹配值,同时范围子模式(subpattern)继续选分支
n @ 1..=12 => format!("small: {n}"),
n @ 13..=99 => format!("medium: {n}"),
_ => format!("large: {n}"),
}
}
Interactive Tools for This Topic
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.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.
FAQ
- How do you run Bind Subpatterns With @ In Match?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.