0PricingLogin
Learn Rust Coding · Lesson

Growing and Shrinking

Insert, remove, and resize.

Vectors Can Change Size

A key feature of vectors is that they change size at runtime. You can add elements when you have more data and remove them when you no longer need them.

Every size change requires the vector to be declared mut.

Growing With push

The push method adds a single element to the end, growing the vector by one. This is the most common way to grow.

Below the vector grows from length 0 to length 3.

fn main() {
    let mut v = Vec::new();
    v.push("a");
    v.push("b");
    v.push("c");
    println!("len = {}", v.len());
}

All lessons in this course

  1. Creating and Filling Vectors
  2. Indexing and Iterating
  3. Growing and Shrinking
  4. Vectors of Structs
← Back to Learn Rust Coding