问题描述
我有一个未知大小的数组,我想获取该数组的一部分并将其转换为静态大小的数组:
I have an array of an unknown size, and I would like to get a slice of that array and convert it to a statically sized array:
fn pop(barry: &[u8]) -> [u8; 3] {
barry[0..3] // expected array `[u8; 3]`, found slice `[u8]`
}
我该怎么做?
推荐答案
您可以使用 TryInto
trait(在 Rust 1.34 中稳定):
You can easily do this with the TryInto
trait (which was stabilized in Rust 1.34):
use std::convert::TryInto;
fn pop(barry: &[u8]) -> [u8; 3] {
barry.try_into().expect("slice with incorrect length")
}
但更好的是:无需克隆/复制您的元素!实际上可以得到一个 &[u8;3]
来自 &[u8]
:
But even better: there is no need to clone/copy your elements! It is actually possible to get a &[u8; 3]
from a &[u8]
:
fn pop(barry: &[u8]) -> &[u8; 3] {
barry.try_into().expect("slice with incorrect length")
}
正如其他答案中提到的,如果 barry
的长度不是 3,您可能不想惊慌,而是优雅地处理此错误.
As mentioned in the other answers, you probably don't want to panic if the length of barry
is not 3, but instead handle this error gracefully.
这要归功于相关特征的这些 impls TryFrom
(在 Rust 1.47 之前,这些只存在于长度不超过 32 的数组):
This works thanks to these impls of the related trait TryFrom
(before Rust 1.47, these only existed for arrays up to length 32):
impl<'_, T, const N: usize> TryFrom<&'_ [T]> for [T; N]
where
T: Copy,
impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N]
impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N]
这篇关于如何在 Rust 中获取切片作为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!