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

查看:437
本文介绍了如何在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] // mismatched types: expected `[u8, ..3]` but found `&[u8]`
}

我该怎么做?

推荐答案

您可以使用

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]中获取&[u8; 3]:

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.

这要归功于相关特征

This works thanks to these impls (where $N is just an integer between 1 and 32) of the related trait TryFrom:

impl<'a, T> TryFrom<&'a [T]> for &'a [T; $N]
  type Error = TryFromSliceError;

impl<'a, T: Copy> TryFrom<&'a [T]> for [T; $N]
  type Error = TryFromSliceError;

这篇关于如何在Rust中获取切片作为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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