expression

Validate a byte before constructing bool

A Rust bool has only two valid representations. External data may contain other bytes, so interpret it through a checked conversion. This policy accepts only the encodings 0 and 1; other protocols may define a different mapping. Expected stdout (not executed): Some(true) None Common mistake: Using unsafe to manufacture a bool with representation 2 and validating it afterward.

Formal Syntax & Structure

rust syntaxrust
match byte { 0 => Some(false), 1 => Some(true), _ => None }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    fn decode(value: u8) -> Option<bool> {        match value { 0 => Some(false), 1 => Some(true), _ => None }    }    println!("{:?} {:?}", decode(1), decode(2));}
Rust Reference