How to allocate space for Vec <T> in Rust?
I want to create Vec<T>and make some space for this, 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 that I can create an empty one Vec<T>and fill it with pushes, but I do not want to do this, because I do not always know when I write a value to index iif the value has already been inserted there. I do not want to write, for obvious performance reasons, something like:
if i >= len(v) {
v.push(x);
} else {
v[i] = x;
}
And of course, I cannot use the syntax vec!.
+4
3 answers
vec![elem; count] , , .
Vec::with_capacity() , . , , , push() , push() :
fn main() {
let mut v = Vec::with_capacity(10);
for i in 0..10 {
v.push(i);
}
println!("{:?}", v);
}
collect() . :
fn main() {
let v: Vec<_> = (1..10).collect();
println!("{:?}", v);
}
, , (, ). Vec::with_capacity() + set_len() :
fn main() {
let mut v = Vec::with_capacity(10);
unsafe { v.set_len(10); }
for i in 0..10 {
v[i] = i;
}
println!("{:?}", v);
}
, , - , . , ( ). , mem::uninitialized().
+11