相关疑难解决方法(0)

有没有一种很好的方法将Vec <T>转换为数组?

有没有一种很好的方法将Vec<T>大小转换S为类型数组[T; S]?具体来说,我正在使用一个返回128位散列的函数作为a Vec<u8>,它总是长度为16,我想将散列作为a处理[u8, 16].

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

rust

23
推荐指数
1
解决办法
2万
查看次数

我如何收集到阵列?

我想调用.map()一系列枚举:

enum Foo {
    Value(i32),
    Nothing,
}

fn main() {
    let bar = [1, 2, 3];
    let foos = bar.iter().map(|x| Foo::Value(*x)).collect::<[Foo; 3]>();
}
Run Code Online (Sandbox Code Playgroud)

但编译器抱怨:

error[E0277]: the trait bound `[Foo; 3]: std::iter::FromIterator<Foo>` is not satisfied
 --> src/main.rs:8:51
  |
8 |     let foos = bar.iter().map(|x| Foo::Value(*x)).collect::<[Foo; 3]>();
  |                                                   ^^^^^^^ a collection of type `[Foo; 3]` cannot be built from an iterator over elements of type `Foo`
  |
  = help: the trait `std::iter::FromIterator<Foo>` is not implemented for `[Foo; 3]`
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

rust

15
推荐指数
9
解决办法
2万
查看次数

标签 统计

rust ×2