如何初始化向量数组? [英] How do I initialize an array of vectors?
问题描述
我想创建一个向量数组:
I would like to create an array of vectors:
fn main() {
let v: [Vec<u8>; 10] = [Vec::new(); 10];
}
但是,编译器给我这个错误:
However, the compiler gives me this error:
error[E0277]: the trait bound `std::vec::Vec<u8>: std::marker::Copy` is not satisfied
--> src/main.rs:2:28
|
2 | let v: [Vec<u8>; 10] = [Vec::new(); 10];
| ^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `std::vec::Vec<u8>`
|
= note: the `Copy` trait is required because the repeated element will be copied
推荐答案
您不能使用 [expr; N]
由于Rust的所有权模型而对非 Copy
类型的初始化语法-它仅执行一次表达式,而对于非 Copy
类型不能仅将字节复制N次,它们只能在一个位置拥有。
You cannot use the [expr; N]
initialisation syntax for non-Copy
types because of Rust’s ownership model—it executes the expression once only, and for non-Copy
types it cannot just copy the bytes N times, they must be owned in one place only.
您将需要:
-
将其明确写出十遍:
let v:[Vec< u8> ;; 10] = [vec![],vec![],vec![],vec![],vec![],vec![],vec![],vec![],vec![],vec ![]] $code>或
Write it out explicitly ten times:
let v: [Vec<u8>; 10] = [vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![]]
, or
使用类似矢量的东西代替数组: std :: iter :: repeat(vec![])。take(10).collect ::< Vec< _>>()
。
Use something like a vector instead of the array: std::iter::repeat(vec![]).take(10).collect::<Vec<_>>()
.
另请参见:
- Initialize a large, fixed-size array with non-Copy types
这篇关于如何初始化向量数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!