0Pricing
Learn Rust Coding · Lesson

Creating and Filling Vectors

Build Vecs and push items.

What Is a Vector?

A vector is a growable list of values, all of the same type. Unlike a fixed-size array, a vector can shrink or grow while your program runs.

In Rust the type is written Vec<T>, where T is the type of element it holds, like Vec<i32> for integers.

An Empty Vector

You can make a fresh, empty vector with Vec::new(). Because it has no values yet, Rust cannot guess the element type, so you usually annotate it.

Here we tell Rust this vector will hold i32 integers.

fn main() {
    let v: Vec<i32> = Vec::new();
    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