Creating a vector of zeros for a specific size

To initialize a vector of zeros (or any other constant value) of a given length, you can use the vec! macro:

let len = 10;
let zero_vec = vec![0; len];

That said, your function worked for me after just a couple syntax fixes:

fn zeros(size: u32) -> Vec<i32> {
    let mut zero_vec: Vec<i32> = Vec::with_capacity(size as usize);
    for i in 0..size {
        zero_vec.push(0);
    }
    return zero_vec;
}

uint no longer exists in Rust 1.0, size needed to be cast as usize, and the types for the vectors needed to match (changed let mut zero_vec: Vec<i64> to let mut zero_vec: Vec<i32>.

Leave a Comment