Loop, While, For — Rust

A loop runs the same block of code many times, and each time is one round. loop repeats until break (the command that leaves), and break value; makes the loop…

At rush hour, the cook at Rusdi's Pancake Stall makes egg pancakes one after another with the same steps every time: crack 3 eggs, mix, fry, repeat. He doesn't need a new recipe each time. All he needs to know is when to stop.

In code, repeating like this is called a loop: the same block of code runs many times. Each time the loop's body runs is called one round. Rust has three kinds of loop: loop, while and for. They differ in how they stop, like three different orders to the cook:

loop: repeat until break

How many egg pancakes can be made from a stock of 250 eggs, if one pancake uses 3 eggs? This program calculates it:

fn main() {
    let mut egg_stock: u32 = 250;
    let mut count = 0;
    let made = loop {
        if egg_stock < 3 {
            break count;
        }
        egg_stock -= 3;
        count += 1;
    };
    println!("Egg Pancakes made: {}", made);
    println!("Eggs left: {}", egg_stock);
}

The output:

Egg Pancakes made: 83
Eggs left: 1

while: as long as the condition holds

Now the stock is only 10 eggs, and each order is printed:

fn main() {
    let mut egg_stock = 10;
    let mut orders = 0;
    while egg_stock >= 3 {
        egg_stock -= 3;
        orders += 1;
        println!("Order {}: eggs left {}", orders, egg_stock);
    }
    println!("Eggs left: {}", egg_stock);
}

The output:

Order 1: eggs left 7
Order 2: eggs left 4
Order 3: eggs left 1
Eggs left: 1

This table shows what happens in each round:

Round Check egg_stock >= 3 egg_stock after orders
1 10 >= 3, true 7 1
2 7 >= 3, true 4 2
3 4 >= 3, true 1 3
4 1 >= 3, false: stop 1 3
error: Rust has no postfix increment operator
 --> src/main.rs:6:15
  |
6 |         orders++;
  |               ^^ not a valid postfix operator
  |
help: use `+= 1` instead
  |
6 -         orders++;
6 +         orders += 1;
  |

for and ranges

Rusdi wants to print three portion lines, and he tries two ways. Before you look at the output, guess: how many lines does for portion in 1..3 { println!("Portion {}", portion); } print?

fn main() {
    for portion in 1..=3 {
        println!("Portion {}", portion);
    }
    for portion in 1..3 {
        println!("Portion {}", portion);
    }
}

The output:

Portion 1
Portion 2
Portion 3
Portion 1
Portion 2

for over an array: values or borrows

for can also take an array's items one by one:

fn main() {
    let prices = [32, 38, 5];
    let mut total = 0;
    for p in prices {
        total += p;
    }
    println!("Total: {}", total);
    for (i, p) in prices.iter().enumerate() {
        println!("{}: {}", i, p);
    }
}

The output:

Total: 75
0: 32
1: 38
2: 5

.iter().enumerate() gives pairs of (position, item), starting at 0. for (i, p) puts the position in i and the item in p. For numbers, prices can still be used after for p in prices, because each number is copied. A String is different: it is moved, like the order note that moved to kitchen in the first lesson. Here is a queue of two notes:

fn main() {
    let queue = [String::from("Sweet Pancake"), String::from("Egg Pancake")];
    for order in queue {
        println!("Cooking: {}", order);
    }
    println!("Queue: {}", queue.len());
}

The compiler refuses it:

error[E0382]: borrow of moved value: `queue`
 --> src/main.rs:6:27
  |
2 |     let queue = [String::from("Sweet Pancake"), String::from("Egg Pancake")];
  |         ----- move occurs because `queue` has type `[String; 2]`, which does not implement the `Copy` trait
3 |     for order in queue {
  |                  ----- `queue` moved due to this implicit call to `.into_iter()`
...
6 |     println!("Queue: {}", queue.len());
  |                           ^^^^^ value borrowed here after move
  |
help: consider iterating over a slice of the `[String; 2]`'s content to avoid moving into the `for` loop
  |
3 |     for order in &queue {
  |                  +

for order in queue moves each note into order, so after the loop queue has moved and can't be used again. That is what borrow of moved value means: the code uses a value that was already moved. The compiler's suggestion is right: for order in &queue only borrows each note, without moving it. With the &, the program prints Cooking: Sweet Pancake, Cooking: Egg Pancake, then Queue: 2.

break, continue and labels

continue skips the rest of this round and goes on to the next one. for table in 1..=5 with if table == 3 { continue; } delivers orders to tables 1, 2, 4 and 5: table 3 is skipped.

A loop inside a loop needs care: a plain break only leaves the innermost loop, the one furthest inside. To leave all of them at once, give the outer loop a label (a name). In this program, the outer loop runs for tables 1 to 3, and the inner loop for portions 1 and 2 at each table:

fn main() {
    let mut egg_stock = 7;
    'orders: for table in 1..=3 {
        for portion in 1..=2 {
            if egg_stock < 3 {
                println!("Out of eggs at table {} portion {}", table, portion);
                break 'orders;
            }
            egg_stock -= 3;
            println!("Table {} portion {}: eggs left {}", table, portion, egg_stock);
        }
    }
}

The output:

Table 1 portion 1: eggs left 4
Table 1 portion 2: eggs left 1
Out of eggs at table 2 portion 1

⚠️ Loops that run one short, one too many, or never stop

TL;DR: A loop runs the same block of code many times, and each time is one round. loop repeats until break (the command that leaves), and break value; makes the loop produce a value (let made = loop { ... };). while condition { } checks a bool condition before each round, so the variable in the condition must change inside the loop. for x in 1..=3 runs for each number in the range (a run of numbers) 1 to 3, including 3. for x in 1..3 stops at 2 (0..3 runs three times). for p in prices takes the items of the array prices one by one. A String item is moved into the loop, so borrow the items with & before the array's name, as in &queue. continue skips the rest of one round, break leaves the innermost loop, and break 'label; leaves the loop with that label (name). Rust has no ++: write += 1.

⚡ loop, until break

Write:

let made = loop {
    if egg_stock < 3 {
        break count;
    }
    egg_stock -= 3;
    count += 1;
};

Meaning: This code counts how many egg pancakes can be made: each round (each time the loop's body runs) takes 3 eggs from egg_stock and adds 1 to count. loop itself has no condition: it repeats forever, and the only way out is break. break count; leaves carrying a value, so made can store it. Because this loop produces a value, its let line ends with };.

⚡ while, as long as the condition holds

Write:

while egg_stock >= 3 {
    egg_stock -= 3;
    orders += 1;
}

Meaning: while repeats as long as its condition is true. The condition egg_stock >= 3 is checked before each round. So egg_stock must change inside the loop. If it doesn't, the condition stays true and the loop never stops. Rust has no ++ as JavaScript does: write += 1.

⚡ for and ranges

Guess first: for portion in 1..3 runs its body once for each number in the range (a run of numbers) 1..3. How many times does the body run?

Twice, for 1 and 2. 1..3 stops before its end. Only 1..=3 includes 3.

Meaning: Use for when the number of rounds is known from the start. portion is made fresh in every round, with no let or mut.

What you will learn