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.
While
vec![elem; count]
from the accepted answer is sufficient to create a vector with all elements equal to the same value, there are other convenience functions.Vec::with_capacity()
creates a vector with the given capacity but with zero length. It means that until this capacity is reached,push()
calls won't reallocate the vector, makingpush()
essentially free:You can also easily
collect()
a vector from an iterator. Example:And finally, sometimes your vector contains values of primitive type and is supposed to be used as a buffer (e.g. in network communication). In this case you can use
Vec::with_capacity()
+set_len()
unsafe method:Note that you have to be extra careful if your vector contains values with destructors or references - it's easy to get a destructor run over a uninitialized piece of memory or to get an invalid reference this way. It will also work right if you only use initialized part of the vector (you have to track it yourself now). To read about all the possible dangers of uninitialized memory, you can read the documentation of
mem::uninitialized()
.You can use the first syntax of the
vec!
macro, specificallyvec![elem; count]
. For example:will create a
Vec<_>
containing 101
s (the type_
will be determined later or default toi32
). Theelem
given to the macro must implementClone
. Thecount
can be a variable, too.There is the
Vec::resize
method:This code resizes an empty vector to 1024 elements by filling with the value
7
: