expression

Checked fixed-width byte parsing

Convert a byte slice into an array only if the expected field length matches. Reject short or long input rather than panicking or silently discarding data. Expected stdout (not executed): Some(256) None Common mistake: A correct byte count does not validate higher-level protocol meaning.

Formal Syntax & Structure

rust syntaxrust
let bytes: [u8; 4] = input.try_into()?;

Working Example

Example Snippetrust
fn parse(input: &[u8]) -> Option<u32> {    let bytes: [u8; 4] = input.try_into().ok()?;    Some(u32::from_be_bytes(bytes))}fn main() {    println!("{:?}", parse(&[0, 0, 1, 0]));    println!("{:?}", parse(&[0, 1]));}
Rust Reference