Reputation: 347
How do you create an array, in rust, whose size is defined at run time?
Basically, how do you convert in rust the following code:
void f(int n){ return std::vector<int>(n); }
?
This is not possible in rust:
let n = 15;
let board: [int, ..n];
Note: I saw that it was impossible to do this in a simple manner, here, but I refuse to accept that such a simple thing is impossible :p
Thanks a lot!
Upvotes: 3
Views: 3792
Reputation: 347
Never-mind, I found it the way:
let n = 15; // number of items
let val = 17; // value to replicate
let v = std::vec::from_elem(val, n);
Upvotes: 3
Reputation: 1639
The proper way in modern Rust is vec![value; size]
.
Values are cloned, which is quite a relief compared to other languages that casually hand back a vector of references to the same object. E.g. vec![vec![]; 2]
creates a vector where both elements are independent vectors, 3 vectors in total. Python's [[]] * 2
creates a vector of length 2 where both elements are (references to) the same nested vector.
Upvotes: 0