kota's memex

A vector allows you to store a variable number of values next to each other. This is rust's "resizable array" and it is part of rust's standard library.

let mut v: Vec<i32> = Vec::new();

v.push(1);
v.push(2);
v.push(3);
v.push(4);

vec! macro

If you want to create a vector with initial values rust has a macro which will infer the type for you:

let v = vec![1, 2, 3]; // Vec<i32>

add

v.push(42)

read

There are two ways to reference a value stored in a vector: via indexing or by using the get method. Vectors, like arrays, are zero indexed.

let v = vec![1, 2, 3, 4, 5];

let third: &i32 = &v[2];
println!("The third element is {third}");

let third: Option<&i32> = v.get(2);
match third {
    Some(third) => println!("The third element is {third}"),
    None => println!("There is no third element."),
}

iterating over values

immutable

let v = vec![100, 32, 57];
for i in &v {
    println!("{i}");
}

mutable

let mut v = vec![100, 32, 57];
for i in &mut v {
    *i += 50;
}

Iterating over a vector, whether immutably or mutably, is safe because of the borrow checker’s rules. If we attempted to insert or remove items in the for loop bodies we would get a compiler error.

stack allocated vector

In some cases it would be helpful to store a "small vector", up to a certain size, on the stack: https://crates.io/crates/smallvec