Editor's note: This question predates Rust 1.0 and syntax and methods have changed since then. Some answers account for Rust 1.0.
I have a function which I would like to have modify a vector in place.
fn f(v: &mut Vec<int>) {
v = Vec::from_elem(10 as uint, 0i);
}
fn main() {
let mut v: Vec<int> = Vec::new();
f(&mut v);
}
But this fails to compile. Specifically, I would like to resize v
to contain 10 elements of value zero. What am I doing wrong?
In Rust vectors has a built in function that retrieve the length of vectors, the function is len (). fn main () { let a = vec! [ 1, 2, 3 ]; println! ( "Vector a length is = {} ", a. len ()); } In this page (written and validated by A. Gawali) you learned about How to get the length of vector in Rust? . What's Next?
In Rust, it's more common to pass slices as arguments rather than vectors when you just want to provide read access. ... However, if the vector's length is increased to 11, it will have to reallocate, which can be slow. For this reason, it is recommended to use Vec::with_capacity whenever possible to specify how big the vector is expected to get.
This is a low-level operation that maintains none of the normal invariants of the type. Normally changing the length of a vector is done using one of the safe operations instead, such as truncate, resize, extend, or clear. new_len must be less than or equal to capacity (). The elements at old_len..new_len must be initialized.
If a vector’s length exceeds its capacity, its capacity will automatically be increased, but its elements will have to be reallocated. For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10 more elements.
Use the clear
and resize
methods. (This seems to be the right answer as of Rust 1.0 and 1.5, respectively.)
fn f(v: &mut Vec<u32>) {
// Remove all values in the vector
v.clear();
// Fill the vector with 10 zeros
v.resize(10, 0);
}
fn main() {
let mut v: Vec<u32> = Vec::new();
f(&mut v);
assert!(v == [0,0,0,0,0,0,0,0,0,0]);
}
Editor's note: This answer predates Rust 1.0 and is no longer necessarily accurate. Other answers still contain valuable information.
You're looking for the grow
method.
let mut vec = vec![1i,2,3];
vec.grow(4, &10);
println!("{}", vec);
Or a combination of grow
and clear
.
You can browse the docs here: http://static.rust-lang.org/doc/master/std/vec/struct.Vec.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With