How to convert a slice into an array reference?

2020-01-27 08:35发布

I have an &[u8] and would like to turn it into an &[u8; 3] without copying. It should reference the original array. How can I do this?

3条回答
来,给爷笑一个
2楼-- · 2020-01-27 08:50

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]
}
查看更多
该账号已被封号
3楼-- · 2020-01-27 08:52

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);
}
查看更多
Emotional °昔
4楼-- · 2020-01-27 08:53

Just to re-emphasize, this can't be done without unsafe code because you don't know until runtime that the slice has three elements in it.

fn slice_to_arr3<T>(slice: &[T]) -> Option<&[T; 3]> {
    if slice.len() == 3 {
        Some(unsafe { &*(slice as *const [T] as *const [T; 3]) })
    } else {
        None
    }
}

This can't be generic over the length of the array until const generics are implemented.

查看更多
登录 后发表回答