Or-Patterns Match Multiple Variants

A single arm can list several values with | and nest them inside tuple or enum patterns, so grouped classification stays one exhaustive match.

RustData Integrity

Code

rustsnippet
32 lines
#[derive(Debug, Clone, Copy)]
enum Level {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}

// or-patterns:一个分支同时匹配多个值,也允许嵌在更深的元组位置
fn keep(record: (Level, Option<&str>)) -> bool {
    match record {
        (Level::Error, _) => true,
        (Level::Warn, Some("prod")) | (Level::Warn, Some("staging")) => true,
        (Level::Info, Some("prod")) => true,
        (Level::Debug, _) | (Level::Trace, _) => false,
        _ => false,
    }
}

fn main() {
    let records = [
        (Level::Error, None),
        (Level::Warn, Some("prod")),
        (Level::Warn, Some("dev")),
        (Level::Info, Some("prod")),
        (Level::Debug, Some("prod")),
    ];
    for (level, env) in records {
        println!("{:?} {env:?} -> keep: {}", level, keep((level, env)));
    }
}

How the snippet works

The working surface is the functions keep and main — everything else is wiring.

Repetition is confined to for (level, env) in records — the rest of the file is straight-line. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Applying it

Entry signature: fn keep(record: (Level, Option<&str>)

The entry point wires keep together — run it once and the whole demo flows.

Statements that matter

fn keep(record: (Level, Option<&str>)) -> bool {
    match record {
        (Level::Error, _) => true,
        (Level::Warn, Some("prod")) | (Level::Warn, Some("staging")) => true,
        (Level::Info, Some("prod")) => true,
        (Level::Debug, _) | (Level::Trace, _) => false,
        _ => false,
    }
}

Interactive Tools for This Topic

FAQ

How do you run Or-Patterns Match Multiple Variants?
Direct execution is enough; the script has no external requirements.