Skip to content
Theory · Conditions and Loops · lesson 5 of 6

for, ranges and labels

In the previous lesson we kept the pass counter by hand: we set up a variable, added one to it and checked a condition. The for loop does all of this itself.

Picture a coach who wrote the plan in advance: laps one through four. The runner does not have to count; they take the number of the next lap from the plan. For for, such a plan is a range, a row of whole numbers from one bound to another. for puts each number of the range into a variable in turn and runs its block with it:

Rust
fn main() {
    let mut a = 0;
    for i in 1..5 {
        a += i;
    }
    let mut b = 0;
    for i in 1..=5 {
        b += i;
    }
    println!("{a} {b}"); // 10 15
}

Let's go through the program:

  1. for i in 1..5 runs the block four times: i is 1, 2, 3 and 4 in turn.
  2. a += i adds these numbers up, and a ends up as 10.
  3. for i in 1..=5 runs the block five times: 5 joins the same numbers.
  4. b ends up as 15, and the program prints 10 15.

You don't declare i with let or increase it by hand. for sets it up itself, and it is visible only inside the loop.

Two kinds of ranges

A range is written with two dots between its bounds. What stands after the dots decides whether the right bound belongs to it.

a..b

The range a..b starts at a itself and stops right before b: 1..5 is 1, 2, 3 and 4. The number of passes is b - a, so 0..n repeats the block exactly n times.

a..=b

The range a..=b includes the right bound: 1..=5 is 1, 2, 3, 4 and 5. You use it when the bound itself must be part of the walk, such as "laps one through five".

Interviewers like to ask how many times a loop over 1..5 runs. The answer "five" is the classic off-by-one error: the right answer is "four".

Counting down

A range always goes up. If the left bound is not less than the right one, the range is empty: for i in 5..0 runs zero times, and the compiler doesn't even warn. To count down, you put the range in parentheses and add .rev():

Rust
for i in (1..=3).rev() {
    println!("{i}");
}
println!("Start!"); // Start!

The loop prints 3, 2 and 1, each number on its own line, and after the loop, Start!. The parentheses around the range are required. Without them the compiler reads 1..=3.rev() as a call of .rev() on the number 3 and reports an error.

Loop labels

A loop can sit inside another loop. Picture a workout: the outer loop is the sets, the inner one is the laps in each set. A plain break in the inner loop ends only the current set, and the runner starts the next one.

To end the whole workout, you give the outer loop a label, a name with an apostrophe and a colon in front of the loop, such as 'rows:. break with this name leaves the named loop. This program searches the multiplication table for the first cell equal to 6:

Rust
'rows: for row in 1..=3 {
    for col in 1..=3 {
        if row * col == 6 {
            println!("{row} x {col}"); // 2 x 3
            break 'rows;
        }
    }
}

Let's go through it step by step:

  1. The outer loop with the label 'rows walks the rows of the table, the inner one walks the columns.
  2. In the row row = 1 the products are 1, 2 and 3, and there is no 6.
  3. In the row row = 2, at col = 3, the product is 6, and the program prints 2 x 3.
  4. break 'rows ends both loops at once: the inner one and the outer one labeled 'rows.

Without the label, break would end only the inner loop. The outer loop would move on to the row row = 3, and the program would also print 3 x 2. A label works with continue too: continue 'rows drops the rest of the current row and moves on to the next pass of the outer loop.

Here the picture is inaccurate: after break 'rows the program does not end the way a workout does. Only the labeled loop and all the loops inside it end, and the lines after the outer loop run as usual. The apostrophe at the start of a label is required: without it the compiler reports error: malformed loop label.

Common mistake

An array is walked by its indices, and the right bound is taken with ..=:

Rust
fn main() {
    let a = [10, 20, 30];
    let mut sum = 0;
    for i in 0..=a.len() { // ✗
        sum += a[i];
    }
    println!("{sum}");
}
TEXT
index out of bounds: the len is 3 but the index is 3

The program builds, but on the fourth pass it stops with a panic. a.len() is the length of the array, here 3, and the indices of its elements are 0, 1 and 2. The range 0..=3 reaches index 3, which the array does not have.

The right bound is 0..a.len(). It is safer still to walk the array itself: for x in a puts its elements into x in turn and never goes past the end.

Key points

  • for i in a..b walks the numbers from a to b, not including b, and a..=b includes b.
  • To count down, put the range in parentheses and reverse it: (1..=3).rev(); the range 5..0 is empty.
  • break and continue act on the nearest loop, while break 'outer and continue 'outer act on the loop labeled 'outer.
  • It is safer to walk an array with for x in a: a loop over 0..=a.len() goes past the end and stops with a panic.