← Back to Rust Course | Chapter 9: Collections | Lesson 1 of 6

Vec Basics

A Vec is a list that can grow or shrink as you add or remove things from it.

Creating a Vec

A Vec is created either with Vec::new() for an empty list or the vec! macro to list initial elements directly.

Example: Creating a Vec

markup
fn main() {
    let numbers = vec![1, 2, 3];
    println!("{:?}", numbers);
}

Pushing and Popping

.push() appends an element to the end of a mutable Vec, and .pop() removes and returns the last element, wrapped in an Option since the vector could be empty.

Example: Pushing and Popping

markup
fn main() {
    let mut stack = Vec::new();
    stack.push(10);
    stack.push(20);
    let last = stack.pop();
    println!("Popped: {:?}, remaining: {:?}", last, stack);
}

Accessing Elements Safely

Direct indexing with [] panics if the index is out of bounds. .get(index) instead returns an Option, letting you handle a missing index without crashing.

Example: Accessing Elements Safely

markup
fn main() {
    let items = vec!["a", "b", "c"];
    println!("{:?}", items.get(1));
    println!("{:?}", items.get(10));
}

Iterating Over a Vec

A for loop can iterate directly over a Vec's elements by reference, letting you process each item without taking ownership of the whole vector.

Example: Iterating Over a Vec

markup
fn main() {
    let scores = vec![90, 85, 77];
    for score in &scores {
        println!("Score: {}", score);
    }
}
Common Mistakes
  1. Trying to index past the end of a Vec, which panics at runtime instead of returning a default value.
  2. Forgetting Vec::new() needs mut on the binding before you can push new elements onto it.
  3. Using vec[i] when the index might be out of bounds, instead of the safer .get(i) which returns an Option.
Chapter Summary
  • Vec<T> is a growable, heap-allocated list of elements of type T.
  • vec![...] is a convenient macro for creating a Vec with initial elements.
  • .push() adds an element to the end; .pop() removes and returns the last one.
  • Indexing with [] panics on an out-of-bounds index, while .get() returns Option safely.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.