有没有一种好方法来转换 Vec T ?到一个数组? [英] Is there a good way to convert a Vec<T> to an array?

查看:28
本文介绍了有没有一种好方法来转换 Vec T ?到一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种好方法可以将大小为 SVec 转换为 [T; 类型的数组?S]?具体来说,我使用的函数将 128 位哈希作为 Vec 返回,它的长度总是为 16,我想将哈希作为 处理[u8, 16].

Is there a good way to convert a Vec<T> with size S to an array of type [T; S]? Specifically, I'm using a function that returns a 128-bit hash as a Vec<u8>, which will always have length 16, and I would like to deal with the hash as a [u8, 16].

是否有类似于 as_slice 方法的内置方法可以给我我想要的东西,或者我应该编写自己的函数来分配一个固定大小的数组,遍历复制每个元素的向量, 并返回数组?

Is there something built-in akin to the as_slice method which gives me what I want, or should I write my own function which allocates a fixed-size array, iterates through the vector copying each element, and returns the array?

推荐答案

数组必须完全初始化,因此您很快就会担心将元素过多或过少的向量转换为数组时该怎么办.这些例子简直让人恐慌.

Arrays must be completely initialized, so you quickly run into concerns about what to do when you convert a vector with too many or too few elements into an array. These examples simply panic.

截至 Rust 1.51 你可以参数化数组的长度.

As of Rust 1.51 you can parameterize over an array's length.

use std::convert::TryInto;

fn demo<T, const N: usize>(v: Vec<T>) -> [T; N] {
    v.try_into()
        .unwrap_or_else(|v: Vec<T>| panic!("Expected a Vec of length {} but it was {}", N, v.len()))
}

截至 Rust 1.48,每个尺寸都需要一个专门的实现:

As of Rust 1.48, each size needs to be a specialized implementation:

use std::convert::TryInto;

fn demo<T>(v: Vec<T>) -> [T; 4] {
    v.try_into()
        .unwrap_or_else(|v: Vec<T>| panic!("Expected a Vec of length {} but it was {}", 4, v.len()))
}

从 Rust 1.43 开始:

As of Rust 1.43:

use std::convert::TryInto;

fn demo<T>(v: Vec<T>) -> [T; 4] {
    let boxed_slice = v.into_boxed_slice();
    let boxed_array: Box<[T; 4]> = match boxed_slice.try_into() {
        Ok(ba) => ba,
        Err(o) => panic!("Expected a Vec of length {} but it was {}", 4, o.len()),
    };
    *boxed_array
}

另见:

这篇关于有没有一种好方法来转换 Vec T ?到一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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