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: "Keep making them until I say stop."while: "Keep making them while there are enough eggs."for: "Make one for each table, table 1 to 3."
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
loop { ... }itself has no condition: it repeats its body forever. The only way out isbreak, the command that leaves a loop.break count;leaves the loop carrying a value, solet made = loop { ... };stores it. This works likeifas an expression in the previous lesson: the loop produces a value. That is why there is a semicolon after the closing}.- 83 pancakes use 83 × 3 = 249 eggs, so 1 egg is left, and 1 isn't enough for the next pancake.
- Forgetting
breakmeans the program never finishes. Stop it by pressing Ctrl+C in the terminal. while true { }(thewhileform comes below) runs too, but the compiler warnsdenote infinite loops with `loop { ... }`. That means: for a loop with no end, writeloop.
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 |
- The condition is checked before each round. As soon as the condition is false, Rust goes on to the line after the
}. The condition must be abool, just likeif. - The variable being checked must change inside the loop. Without
egg_stock -= 3;the condition stays true and the loop never stops. orders += 1;adds 1. Rust has no++. If you writeorders++;as in JavaScript, the compiler refuses it and suggests+= 1:
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 portion in 1..=3runs its body once for each number, and puts that number inportion: 1, then 2, then 3.1..=3is a range (a run of numbers) that includes its end: 1, 2, 3.1..3stops before its end: 1, 2. So the answer to the guess: only two lines print, not three. In the same way,0..3runs three times (0, 1, 2), and its last number is 2.portionis made fresh in every round, so it needs noletormut. Inside the loop,portionis used like any variable, for exampleportion % 2 == 0(remainder of dividing by 2 is zero: even).- Use
forwhen the number of rounds is known from the start. Withfor, you don't increase a counter yourself (likeorders += 1), so there is nothing to forget.
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
- A label has a single quote in front and a colon after:
'orders:.break 'orders;leaves the loop with that name. - Without the label,
break;only stopsfor portion, then the table loop goes on to table 3 and prints one more line:Out of eggs at table 3 portion 1.
⚠️ Loops that run one short, one too many, or never stop
- A range one short.
1..15stops at 14. For 1 to 15, write1..=15. - Writing
i++. Rust has no++or--. Usei += 1andi -= 1. - A while that never stops. The variable in its condition must change inside the loop.
- An array of Strings moved away.
for x in queuemoves its items. Usefor x in &queuewhen the array is still needed. - The order of the multiple checks. In the FizzBuzz exercise, 15 divides by both 3 and 5, so check
i % 15 == 0first. Ifi % 3 == 0is checked first, 15 printsFizz.
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.