← 中文资源

简体中文版本

Rust match 范围与守卫

用字面量、守卫、范围与通配符对整数分类,保证 match 穷尽。

阅读英文原文

题目

编写函数用 match 的范围、守卫和变量绑定对整数分类。输入契约:待分类整数;输出契约:negative、zero、small、medium 或 large 字符串。公开样例 0 期望 "zero"。隐藏测试:-5 得 "negative";42 得 "medium"。

解题思路

分支从具体到宽泛排列:0 字面量、带守卫的负数、1..=10、11..=100、最后 _ 兜底。match 自上而下取第一个匹配分支,范围用 ..= 表示闭区间。

参考实现要点

match n { 0 => "zero", n if n < 0 => "negative", 1..=10 => "small", 11..=100 => "medium", _ => "large" },每支返回 to_string()。守卫分支绑定 n 后加条件,不满足时继续尝试后续分支。

常见错误

原文指出非穷尽 match 会编译失败,需要时加 _ 兜底。另一个坑是分支顺序:若把 _ 放在最前面,后面的范围永远不可达,编译器会警告且分类结果全错;具体模式必须排在宽泛模式之前。

验证方式

用 rustc 编译,测试 0、-5、42、5、100、101 等边界值,断言分类;再检查编译器是否对不可达分支给出警告。

代码示例

fn classify(n: i32) -> String {
    match n {
        0 => "zero".to_string(),
        n if n < 0 => "negative".to_string(),
        1..=10 => "small".to_string(),
        11..=100 => "medium".to_string(),
        _ => "large".to_string(),
    }
}