gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:20:38 31 4
gpt4 key购买 nike

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

fn pop(barry: &[u8]) -> [u8; 3] {
barry[0..3] // expected array `[u8; 3]`, found slice `[u8]`
}

我该怎么做?

最佳答案

您可以使用 TryInto 轻松做到这一点特征(在 Rust 1.34 中稳定):

// Before Rust 2021, you need to import the trait:
// use std::convert::TryInto;

fn pop(barry: &[u8]) -> [u8; 3] {
barry.try_into().expect("slice with incorrect length")
}

但更好的是:无需克隆/复制您的元素!实际上可以获得 &[u8; 3] 来自&[u8]:

fn pop(barry: &[u8]) -> &[u8; 3] {
barry.try_into().expect("slice with incorrect length")
}

如其他答案中所述,如果 barry 的长度不是 3,您可能不想 panic ,而是优雅地处理此错误。

这要归功于相关特征的这些暗示 TryFrom (在 Rust 1.47 之前,这些仅存在于长度不超过 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]

关于arrays - 如何在 Rust 中将切片作为数组获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49939376/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com