Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the length of a vector in Rust?

Tags:

vector

rust

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?

like image 457
Jim Garrison Avatar asked Aug 08 '14 17:08

Jim Garrison


People also ask

How to get the length of a vector in rust?

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?

When to use slices instead of vectors in rust?

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.

Is it possible to change the length of a vector?

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.

What happens if the length of a vector exceeds its capacity?

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.


2 Answers

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]);
}
like image 185
mfluehr Avatar answered Nov 06 '22 20:11

mfluehr


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

like image 21
A.B. Avatar answered Nov 06 '22 18:11

A.B.