Vectors & Dynamic Collections

🦀 Rust Lesson 8 Intermediate

Arrays in Rust are fixed in size and stored on the stack. Vectors are dynamically resizable arrays stored on the heap.

1 Vector Allocations & Iteration borrowing

Slices are dynamic containers: `let mut v: Vec<i32> = Vec::new();`. Slices allocate heap space, expanding automatically as items are added. When iterating over a vector using a loop, borrow its reference (`&v`) to prevent the loop from taking ownership of the vector and invalidating it.

2 Vector operations Code

Let's run a program illustrating vector creations, dynamic insertions, and iterations:

Rust — Vectors ▶ Run Code
fn main() {
    // Declare vector using vec! macro shorthand
    let mut numbers = vec![10, 20, 30];

    numbers.push(40); // Add elements dynamically
    numbers.push(50);

    println!("Vector data: {:?}", numbers);

    // Iterating by borrowing references
    print!("Iterating: ");
    for num in &numbers {
        print!("{} ", num);
    }
    println!();

    // Access elements safely using .get() returning Option
    match numbers.get(10) {
        Some(val) => println!("Element at index 10: {}", val),
        None => println!("Index 10 is out of bounds!"),
    }
}
3 Code Challenge
Challenge: Write a program that declares a mutable vector of strings containing product names. Add three products. Remove the last product using `pop()` and iterate through the vector to print the remaining items.