Casting `&a[i..i+4]` from `&[u8]` to `&[u8; 4]`, is it safely possible?

As the title, let a: &[u8], it is checked that i > 0 && i + 4 < a.len(), is it possible to cast a[i..i + 4] into &[u8; 4]?

If you already have the known-length &[u8], then use try_into. If you have the full array, you can do …[start ..].first_chunk():

let _: &[u8; 4] = (&a[i..i + 4]).try_into().unwrap();
let _: &[u8; 4] = (&a[i..]).first_chunk().unwrap();

Rust Playground

10 Likes

Interesting resolution :smiley_cat:

As a sometimes-helpful trick, note that you can write &a[i..i+4] as &a[i..][..4], which emphasizes the length of the returned slice and lets you avoid repeating i.

@steffahn's answer is what you actually want here, though!

7 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.