Skip to content
AgileLogics
6 min read

Loops

Prerequisites: Conditionals

Rust has three loop keywords: loop, while, and for.

Syntax

loop {
    // repeats forever until `break`
}

while condition {
    // repeats while condition is true
}

for item in collection {
    // runs once per item
}
  • loop repeats until you break. Because loop is an expression, break value makes the loop produce that value.
  • while checks a condition before each pass.
  • for goes through each item of something iterable: a range, an array, or (later) a vector. It's the loop you'll use most.
  • Ranges — 1..4 is 1, 2, 3 (the end is excluded); 1..=4 includes the end. (1..=3).rev() counts backwards.
  • continue skips to the next pass; break exits the loop.
  • Labels such as 'outer: let break or continue target an outer loop when loops are nested.
  • .iter().enumerate() gives you each item together with its index, as a pair (index, item).

Example

fn main() {
    let mut counter = 0;
    let result = loop {
        counter += 1;
        if counter == 5 {
            break counter * 10;
        }
    };
    println!("loop result: {result}");

    let mut n = 3;
    while n > 0 {
        println!("{n}...");
        n -= 1;
    }
    println!("Liftoff!");

    for i in 1..4 {
        print!("[{i}]");
    }
    println!();

    for i in (1..=3).rev() {
        print!("[{i}]");
    }
    println!();

    let fruits = ["apple", "banana", "cherry"];
    for fruit in fruits {
        println!("{fruit}");
    }
    for (index, fruit) in fruits.iter().enumerate() {
        println!("{index}: {fruit}");
    }

    for i in 1..=6 {
        if i % 2 == 0 {
            continue;
        }
        print!("[{i}]");
    }
    println!();

    'outer: for x in 1..=3 {
        for y in 1..=3 {
            if x * y == 4 {
                break 'outer;
            }
            println!("{x} x {y} = {}", x * y);
        }
    }
}

Expected output

loop result: 50
3...
2...
1...
Liftoff!
[1][2][3]
[3][2][1]
apple
banana
cherry
0: apple
1: banana
2: cherry
[1][3][5]
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2

print! doesn't add a newline, so the bracketed numbers share a line until the println!() that follows each loop.

Common mistakes

  • Returning a value from while. Only loop can break with a value:
error[E0571]: `break` with value from a `while` loop
  • Forgetting mut on a loop counter:
let n = 3;
while n > 0 {
    n -= 1;
}
error[E0384]: cannot assign twice to immutable variable `n`
  • Off-by-one errors with ranges: 1..10 stops at 9. Use 1..=10 to include 10.
  • Looping over indexes (for i in 0..fruits.len()) and then writing fruits[i]. It works, but for fruit in fruits (or .enumerate() if you need the index) is clearer and can't go out of bounds.

Practice

Use a for loop over the range 1 to 10 (inclusive) to add up only the even numbers, then print Sum of even numbers: 30.

Show solution
fn main() {
    let mut sum = 0;
    for n in 1..=10 {
        if n % 2 == 0 {
            sum += n;
        }
    }
    println!("Sum of even numbers: {sum}");
}