Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize an array of vectors?

Tags:

arrays

rust

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 
like image 860
Wim V Avatar asked Dec 10 '14 04:12

Wim V


People also ask

How do you Declare an array of vectors in C++?

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.

What is the correct way of initialising an array?

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.

Can you have an array of vectors?

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.


1 Answers

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:

  1. Write it out explicitly ten times: let v: [Vec<u8>; 10] = [vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![]], or

  2. Use something like a vector instead of the array: std::iter::repeat(vec![]).take(10).collect::<Vec<_>>().

See also:

  • Initialize a large, fixed-size array with non-Copy types
like image 168
Chris Morgan Avatar answered Sep 22 '22 23:09

Chris Morgan