Mem Discriminant Compares Variants

Compare enum variant identity while ignoring payloads with mem::discriminant, so state machines can detect same-stage transitions without PartialEq.

RustData Integrity

Code

rustsnippet
37 lines
use std::mem::discriminant;

#[derive(Debug, PartialEq)]
enum JobState {
    Queued,
    Running { worker: u32 },
    Done,
    Failed { reason: String },
}

fn main() {
    let a = JobState::Running { worker: 1 };
    let b = JobState::Running { worker: 7 };
    let c = JobState::Done;

    // discriminant 只比较变体身份,忽略载荷:worker 不同也算同一阶段
    println!("a/b same variant: {}", discriminant(&a) == discriminant(&b));
    println!("a/c same variant: {}", discriminant(&a) == discriminant(&c));

    // 与 PartialEq 对比:PartialEq 要求载荷也相等
    println!("a == b: {}", a == b);

    // 典型用途:状态机里判断「是否处于同一阶段」而不关心细节
    let history = [
        JobState::Queued,
        JobState::Running { worker: 3 },
        JobState::Running { worker: 9 },
        JobState::Failed { reason: "oom".into() },
    ];
    let mut reruns = 0;
    for pair in history.windows(2) {
        if discriminant(&pair[0]) == discriminant(&pair[1]) {
            reruns += 1;
        }
    }
    println!("consecutive same-stage transitions: {reruns}");
}

What the code does

Count the function main as the entire surface area of Mem Discriminant Compares Variants.

Iteration happens inside for pair in history.windows(2) — everything outside it runs once.

Applying it

The demo output is labeled (a/b same variant:, a/c same variant:, a == b:), so every printed line maps back to its originating operation.

Statements that matter

reruns += 1;

Interactive Tools for This Topic

FAQ

What does Mem Discriminant Compares Variants print when run?
The script runs standalone; its 4 labeled outputs include `a/b same variant:`, `a/c same variant:`, `a == b:`.