【问题标题】:Is there a good way to convert a Vec<T> to an array?有没有将 Vec<T> 转换为数组的好方法?
【发布时间】:2015-04-10 20:59:46
【问题描述】:

有没有一种好方法可以将大小为SVec&lt;T&gt; 转换为[T; S] 类型的数组?具体来说,我使用的函数将 128 位散列返回为 Vec&lt;u8&gt;,其长度始终为 16,我想将散列作为 [u8, 16] 处理。

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

【问题讨论】:

  • 只有一行。使用 itertools:Itertools; my_array.iter_mut().set_from(my_vector.iter().cloned());
  • @donbright 这不会导致内存分配吗?
  • 很抱歉,我不能 100% 确定您的意思....您可以在此处查看生成的汇编程序(单击 ... 运行并点击 ASM):play.rust-lang.org/…
  • 现在回过头来看,根据预期的平台,用户可能能够使用不安全的转换,这在理论上会消除复制(“内存分配”?)..并允许使用字节原样

标签: rust


【解决方案1】:

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

Rust 1.51 开始,您可以对数组的长度进行参数化。

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,每个尺寸都需要一个专门的实现:

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 开始:

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
}

另见:

【讨论】:

  • 对我来说,the trait `std::convert::From&lt;std::boxed::Box&lt;[T]&gt;&gt;` is not implemented for `std::boxed::Box&lt;[T; 3]&gt;` 失败了。这是新的吗? (我提供的向量大小为 3,我已经相应地更改了“演示”功能)。
  • @Alien_AV works for me.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
相关资源
最近更新 更多