TExcelTAD
Home › Rust › Rust For Loops

Rust For Loops

The for loop is the loop you will use most in Rust. It runs its body once for each item produced by something iterable — a range of numbers, an array, a vector, the characters of a string and more.

rust
for item in something_iterable {
    // use item
}

You never manage an index variable or a stop condition yourself, so you cannot accidentally loop one step too far.

Looping over a range

A range describes a sequence of numbers.

Range Produces Includes the end?
1..5 1, 2, 3, 4 no (exclusive)
1..=5 1, 2, 3, 4, 5 yes (inclusive)
(1..=5).rev() 5, 4, 3, 2, 1 yes, in reverse
(0..10).step_by(3) 0, 3, 6, 9 no
rust · try it yourself
fn main() {
    print!("1..5   : ");
    for i in 1..5 {
        print!("{} ", i);
    }
    println!();

    print!("1..=5  : ");
    for i in 1..=5 {
        print!("{} ", i);
    }
    println!();

    print!("reverse: ");
    for i in (1..=5).rev() {
        print!("{} ", i);
    }
    println!();

    print!("step 3 : ");
    for i in (0..10).step_by(3) {
        print!("{} ", i);
    }
    println!();
}
1..5   : 1 2 3 4 
1..=5  : 1 2 3 4 5 
reverse: 5 4 3 2 1 
step 3 : 0 3 6 9 

print! works like println! but does not add a newline, so the numbers stay on one line until we call println!().

Summing with a for loop

A very common pattern is to keep a running total in a mutable variable.

rust · try it yourself
fn main() {
    let mut total = 0;

    for n in 1..=100 {
        total += n;
    }

    println!("1 + 2 + ... + 100 = {}", total);
}
1 + 2 + ... + 100 = 5050

Looping over an array

You can loop directly over the elements of an array. Writing &scores borrows the array, so you can still use it after the loop.

rust · try it yourself
fn main() {
    let scores = [72, 88, 95, 61];
    let mut best = 0;

    for score in &scores {
        if *score > best {
            best = *score;
        }
    }

    println!("Scores: {:?}", scores);
    println!("Best score: {}", best);
}
Scores: [72, 88, 95, 61]
Best score: 95

Because we borrowed the array, each score is a reference (&i32); the * reads the number it points to. You will learn all about references in the Borrowing chapter.

Getting the index with enumerate

Sometimes you need both the position and the value. Call .iter().enumerate() to get pairs of (index, item):

rust · try it yourself
fn main() {
    let planets = ["Mercury", "Venus", "Earth", "Mars"];

    for (index, name) in planets.iter().enumerate() {
        println!("Planet #{}: {}", index + 1, name);
    }
}
Planet #1: Mercury
Planet #2: Venus
Planet #3: Earth
Planet #4: Mars

The (index, name) part is a pattern that unpacks each pair into two variables. Indexes start at 0, so we add 1 for a human-friendly number.

break and continue

These work in for loops just like in loop and while.

rust · try it yourself
fn main() {
    for n in 1..=20 {
        if n % 5 == 0 {
            continue; // skip multiples of 5
        }
        if n > 12 {
            break; // stop completely
        }
        print!("{} ", n);
    }
    println!();
}
1 2 3 4 6 7 8 9 11 12 

Tip: Prefer for over while with a manual index. for x in &list is shorter, can't go out of bounds, and is often faster because Rust can skip bounds checks.

Test yourself

Which numbers does for i in 2..5 produce?

  1. 2, 3, 4, 5
  2. 2, 3, 4
  3. 3, 4, 5
  4. 2, 5

How do you count down from 3 to 1 in a for loop?

  1. for i in 3..1
  2. for i in 3..=1
  3. for i in (1..=3).rev()
  4. for i in -3..-1

What does .enumerate() give you on each iteration?

  1. Only the index
  2. A pair (index, item)
  3. The length of the collection
  4. A reversed item