Matches Macro Compact Pattern Checks
Fold status-code patterns into booleans with the matches macro, using range and or patterns plus Err(_) shape checks without binding values.
Code
fn classify(status: u16) -> &'static str {
// matches! 把模式折叠成布尔值,范围与或模式都可以
if matches!(status, 200..=299) {
"ok"
} else if matches!(status, 401 | 403) {
"unauthorized"
} else if matches!(status, 400..=499) {
"client-error"
} else {
"other"
}
}
fn main() {
for status in [200u16, 204, 401, 404, 500] {
println!("{status}: {}", classify(status));
}
let payload: Result<i32, String> = Err("boom".into());
// 只看枚举形状,不绑定内部值,也不会消耗 payload
assert!(matches!(payload, Err(_)));
println!("payload is Err: {}", matches!(payload, Err(_)));
}Inside the snippet
Matches Macro Compact Pattern Checks reduces to the functions classify and main.
The one repetition in this snippet is the loop for status in [200u16, 204, 401, 404, 500]. Result turns the error into data — visible in the type, handled by the caller.
What to watch for
- The
Resultvalues will not let errors pass silently; each must be matched, unwrapped, or propagated.
Putting it to use
The main signature reads fn classify(status: u16) -> &'static str
Running the file prints labeled results such as payload is Err: — each operation’s effect is visible in the output.
The sequence classify lives in main; running the file triggers it.
Core lines
let payload: Result<i32, String> = Err("boom".into());
fn classify(status: u16) -> &'static str {
// matches! 把模式折叠成布尔值,范围与或模式都可以
if matches!(status, 200..=299) {
"ok"
} else if matches!(status, 401 | 403) {
"unauthorized"
} else if matches!(status, 400..=499) {
"client-error"
} else {
"other"
}
}
assert!(matches!(payload, Err(_)));
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- As `Result` values — each fallible call returns one, and the caller matches or propagates it.
- What does Matches Macro Compact Pattern Checks print when run?
- Running the file directly is enough — expect labeled output lines such as `payload is Err:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.