Match Guards Bindings And Ranges
Refine match arms with or-patterns, numeric ranges, @ bindings that keep the matched value, and guards that reference outer variables.
Code
fn classify(status: u16, retries: u8) -> String {
match status {
// 或模式:多个字面量共用一个分支
200 | 204 => String::from("success"),
// 范围(range)模式 + @ 绑定:命中区间的同时保留原值
code @ 400..=499 => format!("client error {} after {} retries", code, retries),
// guard:分支条件可以引用外部绑定
code if code >= 500 && retries >= 3 => format!("gave up on {}", code),
code => format!("retrying after {}", code),
}
}
fn main() {
let cases = [(200u16, 0u8), (204, 0), (429, 2), (503, 3), (503, 1)];
for (status, retries) in cases {
println!("{}", classify(status, retries));
}
}How it works
Match Guards Bindings And Ranges is built around the functions classify and main.
Iteration happens inside for (status, retries) in cases — everything outside it runs once. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Applying it
The main signature reads fn classify(status: u16, retries: u8) -> String
Running the file executes main, which drives classify in order.
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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Match Guards Bindings And Ranges?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.