← 中文资源

简体中文版本

常量模式与绑定之辨

match 里的常量模式要求路径标识符(大写常量名)才会比较值;小写标识符是捕获一切的全新绑定——同一位置的命名习惯决定语义。

阅读英文原文

实现说明

常量模式与绑定之辨以函数 label、buggy、main为骨架。 match 把每种情况写明白;漏写一个就编译不过。

使用要点

  • 演示输出是带标签的(label(404):、label(500):、buggy(200):),每个操作都会留下自己的一行标注。
  • 执行文件,main 会按顺序走完 label、buggy。

常见问题

运行「常量模式与绑定之辨」会打印什么?

运行文件本身,label(404):、label(500):、buggy(200): 这些前缀各对应一段演示逻辑。

入口签名:fn label(code: u32) -> &'static str

核心语句

fn label(code: u32) -> &'static str {
    // constant patterns: 大写常量名构成路径模式,按值比较
    match code {
        STATUS_NOT_FOUND => "not found",
        _ => "other",
    }
}
fn buggy(code: u32) -> String {
    match code {
        // lowercase identifier 不是常量模式:status_not_found 绑定任意输入
        status_not_found => format!("binding swallowed {}", status_not_found),
    }
}

代码示例

const STATUS_NOT_FOUND: u32 = 404;

fn label(code: u32) -> &'static str {
    // constant patterns: 大写常量名构成路径模式,按值比较
    match code {
        STATUS_NOT_FOUND => "not found",
        _ => "other",
    }
}

fn buggy(code: u32) -> String {
    match code {
        // lowercase identifier 不是常量模式:status_not_found 绑定任意输入
        status_not_found => format!("binding swallowed {}", status_not_found),
    }
}

fn main() {
    println!("label(404): {}", label(404));
    println!("label(500): {}", label(500));
    println!("buggy(200): {}", buggy(200));
    println!("buggy(404): {}", buggy(404));
}