How to convert a slice into an array reference?

They arrayref crate implements this.

Here's an example, you can of course use it in different ways:

#[macro_use]
extern crate arrayref;

/// Get the first 3 elements of `bytes` as a reference to an array
/// **Panics** if `bytes` is too short.
fn first3(bytes: &[u8]) -> &[u8; 3] {
     array_ref![bytes, 0, 3]
}

As of Rust 1.34, you can use TryFrom / TryInto:

use std::convert::TryFrom;

fn example(slice: &[u8]) {
    let array = <&[u8; 3]>::try_from(slice);
    println!("{:?}", array);
}

fn example_mut(slice: &mut [u8]) {
    let array = <&mut [u8; 3]>::try_from(slice);
    println!("{:?}", array);
}

Tags:

Arrays

Slice

Rust