← 中文资源

简体中文版本

non_exhaustive 枚举与通配分支

用 #[non_exhaustive] 标记事件枚举并在匹配时保留 _ 通配分支:上游未来新增变体时落入未知分支优雅降级,调用方 match 不被新增变体打破。

阅读英文原文

实现说明

全部逻辑都在函数 classify、main中。 循环只出现在 for event in &inbox,它的每次迭代处理一个元素。match 一条一条覆盖值的形态——不会意外落到默认分支上。

使用要点

  • main 按顺序串起 classify;运行文件就会把这个流程跑一遍。

常见问题

「non_exhaustive 枚举与通配分支」这个示例怎么运行?

文件自包含:直接运行,没有需要预先安装的依赖。

主要签名是 fn classify(event: &ReleaseEvent) -> &'static str

核心语句

fn classify(event: &ReleaseEvent) -> &'static str {
    match event {
        ReleaseEvent::Deployed { .. } => "shipped",
        ReleaseEvent::RolledBack { .. } => "reverted",
        // 上游未来新增变体会落入这里:调用方 match 无需重写
        _ => "unknown future variant",
    }
}

代码示例

// 非 exhaustive 枚举:上游承诺还会加变体,下游必须留通配分支
#[derive(Debug)]
#[non_exhaustive]
enum ReleaseEvent {
    Deployed { version: String },
    RolledBack { version: String },
}

fn classify(event: &ReleaseEvent) -> &'static str {
    match event {
        ReleaseEvent::Deployed { .. } => "shipped",
        ReleaseEvent::RolledBack { .. } => "reverted",
        // 上游未来新增变体会落入这里:调用方 match 无需重写
        _ => "unknown future variant",
    }
}

fn main() {
    let inbox = [
        ReleaseEvent::Deployed { version: "v2.4.0".into() },
        ReleaseEvent::RolledBack { version: "v2.4.0".into() },
    ];
    for event in &inbox {
        println!("{:?} -> {}", event, classify(event));
    }
}