non_exhaustive Enums And The Wildcard Arm

Match a non_exhaustive enum with a trailing wildcard arm so variants added upstream later degrade gracefully instead of breaking the match.

RustResilience

Code

rustsnippet
26 lines
// 非 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));
    }
}

How it works

Structurally, expect the functions classify and main and nothing else.

Iteration happens inside for event in &inbox — everything outside it runs once. Pattern matching via match forces each shape of the value to be handled.

What to watch for

  • There is no dependency tree here — the platform is the whole dependency.

Using it

The working signature: fn classify(event: &ReleaseEvent) -> &'static str

main sequences classify; executing the file runs that flow once.

Key statements

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

Interactive Tools for This Topic

FAQ

How do you run non_exhaustive Enums And The Wildcard Arm?
The file is self-contained: run it directly, no dependencies to install beforehand.