如何在 Rust 中将切片作为数组获取? [英] How to get a slice as an array in Rust?

查看:37
本文介绍了如何在 Rust 中将切片作为数组获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这要归功于相关特征的这些实现 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 中将切片作为数组获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆