TryFromSliceError
RustERRORCommonType Conversion

Slice length mismatch

Quick Answer

Verify slice length before converting, or use slice indexing to extract the right number of bytes.

What this means

Returned by <[T; N]>::try_from(&[T]) when the slice length does not match the target array length.

Why it happens
  1. 1Byte slice shorter or longer than the target array size
  2. 2Protocol data unexpectedly truncated

Fix

Convert a known-length slice

Convert a known-length slice
let bytes: &[u8] = &data[0..4];
let arr: [u8; 4] = bytes.try_into()
    .map_err(|_| "expected exactly 4 bytes")?;
let value = u32::from_le_bytes(arr);

Why this works

Slicing to the exact length before try_into() eliminates the mismatch.

Code examples
Triggerrust
let a: [u8; 4] = [1u8, 2].as_ref().try_into()?; // wrong length
Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Rust errors