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
Use C-style Array Notation to Declare an Array of Vectors in C++ A fixed array of vectors can be declared by the C-style array brackets notation - [] . This method essentially defines a two-dimensional array with a fixed number of rows and a variable number of columns.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
Therefore, array of vectors is two dimensional array with fixed number of rows where each row is vector of variable length. Each index of array stores a vector which can be traversed and accessed using iterators. Insertion: Insertion in array of vectors is done using push_back() function.
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.
You will need to either:
Write it out explicitly ten times: let v: [Vec<u8>; 10] = [vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![]]
, or
Use something like a vector instead of the array: std::iter::repeat(vec![]).take(10).collect::<Vec<_>>()
.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With