Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

rust - How to convert a slice into an array reference?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...