本文介绍了如何将切片转换为数组引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个&[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);
}
这篇关于如何将切片转换为数组引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!