Slice To Fixed Array With TryInto

Turn a borrowed slice into a fixed-size array with try_into; exact lengths move through, mismatches surface as TryFromSliceError you map to your own error.

RustData Integrity

Code

rustsnippet
22 lines
fn header_length(bytes: &[u8]) -> Result<u32, &'static str> {
    // 借用切片 → 定长数组:长度不符在类型层面报错,不用手工校验下标
    let raw: [u8; 4] = bytes
        .try_into()
        .map_err(|_| "need exactly 4 header bytes")?;
    Ok(u32::from_be_bytes(raw))
}

fn main() {
    let frame = vec![0x00, 0x00, 0x1f, 0x40, 0xff, 0xee];

    println!("header ok: {}", header_length(&frame[..4]).unwrap());
    match header_length(&frame[..3]) {
        Ok(value) => println!("unexpected {value}"),
        Err(reason) => println!("rejected: {reason}"),
    }

    // Vec 整体转定长数组:长度恰好时所有权直接转移
    let owned = vec![1u8, 2, 3, 4];
    let fixed: [u8; 4] = owned.try_into().expect("exact length");
    println!("owned array: {fixed:?}");
}

How the snippet works

Slice To Fixed Array With TryInto reduces to the functions header_length and main.

The Result return type makes both outcomes part of the signature. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

What to watch for

  • Adapting this code means honoring its Result contract: match each one or pass it up with ?.

Applying it

Entry signature: fn header_length(bytes: &[u8]) -> Result<u32, &'static str>

The demo output is labeled (header ok:, unexpected, rejected:), so every printed line maps back to its originating operation.

The demo flow inside main is header_length — run the file to see it end to end.

Statements that matter

fn header_length(bytes: &[u8]) -> Result<u32, &'static str> {
    // 借用切片 → 定长数组:长度不符在类型层面报错,不用手工校验下标
    let raw: [u8; 4] = bytes
        .try_into()
        .map_err(|_| "need exactly 4 header bytes")?;
    Ok(u32::from_be_bytes(raw))
}
match header_length(&frame[..3]) {
    Ok(value) => println!("unexpected {value}"),
    Err(reason) => println!("rejected: {reason}"),
}

Interactive Tools for This Topic

FAQ

How are errors reported?
Through the type system: failures are `Result` variants the caller must consume.
What does Slice To Fixed Array With TryInto print when run?
The script runs standalone; its 4 labeled outputs include `header ok:`, `unexpected`, `rejected:`.