0PricingLogin
Learn Rust Coding · Lesson

Indexing and Iterating

Access and loop over elements.

Reading by Index

Each element in a vector has a position number called an index. Indexes start at 0, so the first element is index 0.

Read an element with square brackets, like v[0] for the first value.

fn main() {
    let v = vec![100, 200, 300];
    println!("first = {}", v[0]);
    println!("third = {}", v[2]);
}

Out of Bounds Panics

Indexing past the end of a vector causes a panic and stops the program. For a vector of length 3, the only valid indexes are 0, 1, and 2.

Asking for v[5] here would crash, so always make sure the index is in range.

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