How to convert a slice into an array reference?

前端 未结 3 1776
感情败类
感情败类 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条回答
  •  -上瘾入骨i
    2020-11-27 08:38

    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);
    }
    

提交回复
热议问题