Dev Notes

Software Development Resources by David Egan.

Rust Vectors

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,];

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>) {
    for (i, el) in v.iter().enumerate() {
        if i != 0 {print!(", ")}
        print!("{}", el);

comments powered by Disqus