3

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!

Community
  • 1
  • 1
OlivierH
  • 385
  • 3
  • 12
  • possible duplicate of [Rust: Creating a vector with non-constant length](http://stackoverflow.com/questions/16745907/rust-creating-a-vector-with-non-constant-length) – Chris Morgan Jan 27 '14 at 23:36
  • Slightly newer answers apply if you [want to create a vector of zeroes](https://stackoverflow.com/questions/29530011/creating-a-vector-of-zeros-for-a-specific-size) – Stein Mar 03 '22 at 11:26

2 Answers2

3

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);
Coder
  • 1,415
  • 2
  • 23
  • 49
OlivierH
  • 385
  • 3
  • 12
0

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.

Stein
  • 1,558
  • 23
  • 30