Dev Notes

Software Development Resources by David Egan.

Rust Vectors


Rust
David Egan

The vec! macro makes initializing vectors convenient:

fn main() {
    let expected = vec![
        0x77, 0xd6, 0x57, 0x62, 0x38, 0x65, 0x7b, 0x20,
        0x3b, 0x19, 0xca, 0x42, 0xc1, 0x8a, 0x04, 0x97,];
    print_vec(&expected);
}

Initialize a vector of size n = 5 setting each element to 42:

let mut my_vec = vec![42; 5]; // Note semicolon seperator

Get an index within a for loop using .iter().enumerate():

fn print_vec(v: &Vec<u8>) {
    print!("[");
    for (i, el) in v.iter().enumerate() {
        if i != 0 {print!(", ")}
        print!("{}", el);
    }
    print!("]");
}

comments powered by Disqus