简体   繁体   中英

How can I change the length of a vector in 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?

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

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM