How to convert a slice into an array reference?

前端 未结 3 1775
感情败类
感情败类 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:36

    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]
    }
    

提交回复
热议问题