'Rust - Vector with size defined at runtime

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!



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stein