Enum Discriminants With Repr U8

Give state enums an explicit u8 backing with #[repr(u8)] so variants map to stable wire values and match stays exhaustive.

RustData Integrity

Code

rustsnippet
34 lines
// repr(u8):变体在内存里固定为 u8,可安全落到协议字段
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TaskState {
    Queued = 0,
    Running = 1,
    Done = 2,
    Failed = 3,
}

impl TaskState {
    fn from_wire(value: u8) -> Option<Self> {
        match value {
            0 => Some(TaskState::Queued),
            1 => Some(TaskState::Running),
            2 => Some(TaskState::Done),
            3 => Some(TaskState::Failed),
            _ => None, // 未知编码显式拒绝
        }
    }

    fn discriminant(self) -> u8 {
        self as u8
    }
}

fn main() {
    for raw in [0u8, 2, 3, 9] {
        match TaskState::from_wire(raw) {
            Some(state) => println!("{} -> {:?} (wire {})", raw, state, state.discriminant()),
            None => println!("{} -> rejected", raw),
        }
    }
}

How it works

Enum Discriminants With Repr U8 comes down to the functions from_wire, discriminant and main.

A single loop drives the file — for raw in [0u8, 2, 3, 9]. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: fn from_wire(value: u8) -> Option<Self>

Running the file executes main, which drives from_wire and discriminant in order.

Key statements

_ => None, // 未知编码显式拒绝
}
match TaskState::from_wire(raw) {
Some(state) => println!("{} -> {:?} (wire {})", raw, state, state.discriminant()),
None => println!("{} -> rejected", raw),
}
fn discriminant(self) -> u8 {
self as u8
}

Interactive Tools for This Topic

FAQ

How do you run Enum Discriminants With Repr U8?
It runs as-is — treat the file as the whole program and execute it.