0Pricing
Learn Rust Coding · Lesson

Indexing and Iterating

Access and loop over elements.

Indexing and Iterating is a free Learn Rust Coding lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Safe Access With get

The get method returns an Option instead of panicking. You get Some(value) if the index exists, or None if it is out of range.

This lets you handle a missing element gracefully.

fn main() {
    let v = vec![1, 2, 3];
    match v.get(5) {
        Some(x) => println!("got {}", x),
        None => println!("no such index"),
    }
}

How Many Elements

The len method gives the number of elements. The last valid index is always len - 1.

Knowing the length helps you loop safely or check bounds before indexing.

fn main() {
    let v = vec![5, 6, 7, 8];
    println!("length = {}", v.len());
    println!("last = {}", v[v.len() - 1]);
}

Looping Over Values

The cleanest way to visit every element is a for loop over a reference to the vector. Using &v borrows the vector so it stays usable afterward.

Each pass binds n to a reference of one element.

fn main() {
    let v = vec![2, 4, 6];
    for n in &v {
        println!("value: {}", n);
    }
}

Looping With Index

When you need the position too, call iter().enumerate(). It yields pairs of (index, value) on each step.

This is perfect for numbered output or rules that depend on position.

fn main() {
    let v = vec!["a", "b", "c"];
    for (i, item) in v.iter().enumerate() {
        println!("{}: {}", i, item);
    }
}

Changing Each Element

To modify values in place, loop over &mut v and the vector must be mut. Each n is a mutable reference, so you dereference it with * to assign.

Here every element is doubled.

fn main() {
    let mut v = vec![1, 2, 3];
    for n in &mut v {
        *n *= 2;
    }
    println!("{:?}", v);
}

Summing a Vector

Iterators make math easy. The iter().sum() method adds all the elements together.

Rust needs to know the result type, so we annotate the total as i32.

fn main() {
    let v = vec![10, 20, 30];
    let total: i32 = v.iter().sum();
    println!("sum = {}", total);
}

First and Last

The first() and last() methods return Option references to the ends of the vector. They give None when the vector is empty.

Using them avoids manual index math and out-of-range crashes.

fn main() {
    let v = vec![7, 8, 9];
    println!("{:?}", v.first());
    println!("{:?}", v.last());
}

Searching With contains

To check whether a value is present, use contains. It takes a reference to the value and returns a bool.

This scans the vector and is a quick way to test membership.

fn main() {
    let v = vec![3, 6, 9];
    println!("has 6? {}", v.contains(&6));
    println!("has 5? {}", v.contains(&5));
}

Slicing a Range

A slice borrows part of a vector using a range, like &v[1..3]. The start is included and the end is excluded.

Slices let you work with a window of elements without copying them.

fn main() {
    let v = vec![10, 20, 30, 40];
    let middle = &v[1..3];
    println!("{:?}", middle);
}

Quick Check

Test your understanding of indexing and iterating.

Recap

You read elements by index, accessed them safely with get, and looped with for, enumerate, and &mut.

You also used sum, first, last, contains, and slices. Next you will grow and shrink vectors.

Frequently asked questions

Is the “Indexing and Iterating” lesson free?

Yes — the full text of “Indexing and Iterating” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.

What will I learn in “Indexing and Iterating”?

Access and loop over elements. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn Rust Coding?

No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Indexing and Iterating” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn Rust Coding lesson?

Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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