How to convert a slice into an array reference?

前端 未结 3 1778
感情败类
感情败类 2020-11-27 08:26

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条回答
  •  一向
    一向 (楼主)
    2020-11-27 08:55

    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(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.

提交回复
热议问题