猿问

如何在Rust中获取切片作为数组?

我有一个未知大小的数组,我想获取该数组的一部分并将其转换为静态大小的数组:


fn pop(barry: &[u8]) -> [u8; 3] {

    barry[0..3] // mismatched types: expected `[u8, ..3]` but found `&[u8]`

}

我该怎么做?


明月笑刀无情
浏览 1360回答 3
3回答

手掌心

您可以轻松地使用TryInto特征(在Rust 1.34中已稳定):fn pop(barry: &[u8]) -> [u8; 3] {&nbsp; &nbsp; barry.try_into().expect("slice with incorrect length")}但更好的是:无需克隆/复制元素!实际上有可能从中获得&[u8; 3]a &[u8]:fn pop(barry: &[u8]) -> &[u8; 3] {&nbsp; &nbsp; barry.try_into().expect("slice with incorrect length")}如其他答案中所述,如果的长度barry不为3,您可能不希望惊慌,而应适当地处理此错误。这要归功于$N相关特征的这些impls(其中仅是1到32之间的整数)TryFrom:impl<'a, T> TryFrom<&'a [T]> for &'a [T; $N]&nbsp; type Error = TryFromSliceError;impl<'a, T: Copy> TryFrom<&'a [T]> for [T; $N]&nbsp; type Error = TryFromSliceError;

慕哥6287543

我们可以使用此辅助函数:use std::convert::AsMut;fn clone_into_array<A, T>(slice: &[T]) -> Awhere&nbsp; &nbsp; A: Default + AsMut<[T]>,&nbsp; &nbsp; T: Clone,{&nbsp; &nbsp; let mut a = A::default();&nbsp; &nbsp; <A as AsMut<[T]>>::as_mut(&mut a).clone_from_slice(slice);&nbsp; &nbsp; a}得到更整洁的语法:fn main() {&nbsp; &nbsp; let original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];&nbsp; &nbsp; let e = Example {&nbsp; &nbsp; &nbsp; &nbsp; a: clone_into_array(&original[0..4]),&nbsp; &nbsp; &nbsp; &nbsp; b: clone_into_array(&original[4..10]),&nbsp; &nbsp; };&nbsp; &nbsp; println!("{:?}", e);}只要T: Default + Clone。如果您知道您的类型实现Copy,则可以使用以下形式:use std::convert::AsMut;fn copy_into_array<A, T>(slice: &[T]) -> Awhere&nbsp; &nbsp; A: Default + AsMut<[T]>,&nbsp; &nbsp; T: Copy,{&nbsp; &nbsp; let mut a = A::default();&nbsp; &nbsp; <A as AsMut<[T]>>::as_mut(&mut a).copy_from_slice(slice);&nbsp; &nbsp; a}panic!如果目标数组和传入的切片的长度不相同,则这两种变体都将。

LEATH

这是一个与您要求的类型签名相匹配的函数。fn pop(barry: &[u8]) -> [u8; 3] {&nbsp; &nbsp; [barry[0], barry[1], barry[2]]}但是由于barry可能少于三个元素,因此您可能需要返回一个Option<[u8; 3]>而不是一个[u8; 3]。fn pop(barry: &[u8]) -> Option<[u8; 3]> {&nbsp; &nbsp; if barry.len() < 3 {&nbsp; &nbsp; &nbsp; &nbsp; None&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; Some([barry[0], barry[1], barry[2]])&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答