Rust Basics

Rust Vectors: Vec<T>

A list that grows while the program runs: push, pop, sort and read items safely.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • vec! and push
  • Indexing vs get
  • sort and pop
vec![3, 1, 4] after two pushes
30
11
42
1push
5push
A Vec grows at the end.

A growable list

A vector, written Vec<T>, is a list that can grow and shrink while the program runs. It is the collection you will use most often in Rust.

vec! creates a vector with starting values and push adds to the end. numbers[2] stops the program if the index does not exist, while get returns None instead. pop removes the last item and returns it inside Some.

Key points

  1. push adds to the end, pop removes from the end.
  2. numbers[10] stops the program if the index is missing.
  3. get(10) returns None instead.

Runnable Rust example

Rust
Run code →
main.rs
fn main() {
    let mut numbers = vec![3, 1, 4];
    numbers.push(1);
    numbers.push(5);

    println!("{:?}", numbers);
    println!("length: {}", numbers.len());
    println!("third: {}", numbers[2]);

    match numbers.get(10) {
        Some(value) => println!("found {value}"),
        None => println!("no item at index 10"),
    }

    numbers.sort();
    let last = numbers.pop();
    println!("{:?} after pop, removed {:?}", numbers, last);
}
Get a Run button for this example Result of running the code
[3, 1, 4, 1, 5]
length: 5
third: 4
no item at index 10
[1, 1, 3, 4] after pop, removed Some(5)

Practice

Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges