本文介绍了如何将切片转换为数组引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 &[u8]
并且想把它变成一个 &[u8;3]
无需复制.它应该引用原始数组.我该怎么做?
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?
推荐答案
从 Rust 1.34 开始,你可以使用 TryFrom
/TryInto
:
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);
}
这篇关于如何将切片转换为数组引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!