expression

Decode an enum discriminant with a checked match

A primitive representation specifies how an enum discriminant is represented, but it does not turn every integer into a valid variant. Map external numbers to declared variants before constructing the enum. Expected stdout (not executed): Some(Run) None Common mistake: Transmuting an unknown discriminant into an enum and then matching it.

Formal Syntax & Structure

rust syntaxrust
#[repr(u8)] + match input

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    #[repr(u8)]    #[derive(Debug)]    enum Mode { Idle = 0, Run = 3 }    fn decode(n: u8) -> Option<Mode> {        match n { 0 => Some(Mode::Idle), 3 => Some(Mode::Run), _ => None }    }    println!("{:?} {:?}", decode(3), decode(2));}
Rust Reference