How to allocate space for a Vec<T> in Rust?
rust, vector
Solution
You can use the first syntax of the `vec!` macro, specifically `vec![elem; count]`. For example:
vec![1; 10]
will create a `Vec<_>` containing 10 `1`s (the type `_` will be determined later or default to `i32`). The `elem` given to the macro must implement `Clone`. The `count` can be a variable, too.
Problem
I want to create a `Vec<T>` and make some room for it, but I don't know how to do it, and, to my surprise, there is almost nothing in the official documentation about this basic type. ``` let mut v: Vec<i32> = Vec<i32>(SIZE); // How do I do this ? for i in 0..SIZE { v[i] = i; } ``` I know I can create an empty `Vec<T>` and fill it with `push`es, but I don't want to do that since I don't always know, when writing a value at index `i`, if a value was already inserted there yet. I don't want to write, for obvious performance reasons, something like : ``` if i >= len(v) { v.push(x); } else { v[i] = x; } ``` And, of course, I can't use the `vec!` syntax either.