简体   繁体   中英

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!

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);

The proper way in modern Rust is vec![value; size] 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. Eg vec![vec![]; 2] 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM