loop and while
In the previous lesson the program chose a road at a fork. Now let's teach it to repeat the same steps.
Picture a runner at a stadium. They run lap after lap on the same track until the coach says "enough". A program often needs to repeat things too: count laps, go through numbers, search for the right value. For this there is the loop, a block of code that runs again and again. We'll call one run of this block a pass.
Rust has three loops: loop, while and for. Let's start with loop: it repeats its block with no condition at all, until break stops it.
fn main() {
let mut lap = 0;
loop {
lap += 1;
if lap == 3 {
break;
}
}
println!("laps: {lap}"); // laps: 3
}Let's go through the program step by step:
let mut lap = 0;sets up a lap counter. It is mutable, because the loop will change it.loop {starts the loop: everything up to the matching}repeats.lap += 1;adds one tolap, the same aslap = lap + 1;.- On the third pass the condition
lap == 3is true, andbreakends the loop. - The program continues after the loop and prints
laps: 3.
Without break this loop would never end. It is called an infinite loop, and that is how you write, for example, a server that keeps waiting for new requests.
break and continue
Two instructions inside the block change the usual course of the passes. Both usually sit inside an if.
break
break ends the whole loop at once. The rest of the block and all later passes are skipped, and the program continues from the line after the loop. The runner leaves the track.
continue
continue skips only the rest of the current pass and starts the next one right away. The loop does not end: the runner cuts the rest of the lap short and runs a new one.
People often mix them up, and the difference is big: break ends the whole loop, continue only the current pass.
A value from loop
A loop often searches for something, and what it finds has to be saved in a variable. In Rust, loop, like if, is an expression. You can write a value after break: break leaves the loop, and this value becomes the value of the whole loop. This program searches for the first number whose square is greater than 50:
let mut n = 1;
let found = loop {
if n * n > 50 {
break n;
}
n += 1;
};
println!("{found}"); // 8Let's go through it step by step:
- The loop checks the numbers in turn: 1, 2, 3 and so on.
- While
n * nis not greater than 50,n += 1moves on to the next number. The square of 7 is 49, and the loop goes on. - The square of 8 is 64, and
break nleaves the loop with the value8. let found =puts the value of the wholeloopintofound, and the program prints8.
break takes the whole expression after it: break n * 2 would give 16, not 8. The loop ends right at break, so the line n += 1 no longer runs on the last pass. The semicolon after } ends the let instruction, as in the line with if.
Here is the same rule on a running track: the runner runs 400-meter laps until reaching 1000 meters, and the loop gives back the number of laps. Press "Next step" and watch when the variable laps appears in the main frame.
1fn main() {2 let mut meters = 0;3 let laps = loop {4 meters += 400;5 println!("{meters} m");6 if meters >= 1000 {7 break meters / 400;8 }9 };10 println!("laps: {laps}");11}
The runner is at the start: meters is 0, and there is no laps variable yet.
Interviewers like to ask this: "How do you return a value from a loop?" The answer: with loop and break with a value, let x = loop { … break value; };.
The while loop
while repeats its block as long as the condition is true. The condition is checked before every pass and, as in if, must have type bool. This program counts how many times 100 has to be divided by 2 with integer division until 1 is left:
let mut n = 100;
let mut steps = 0;
while n > 1 {
n = n / 2;
steps += 1;
}
println!("{steps} steps, n = {n}"); // 6 steps, n = 1The values of n go like this: 100, 50, 25, 12, 6, 3, 1. After the sixth division the condition n > 1 becomes false, and the loop ends without any break.
You use while when the number of passes is not known in advance and depends on what happens inside the loop. Here the runner picture is inaccurate: a runner runs at least one lap, while while checks the condition before the very first pass. If the condition is false right away, the block does not run even once.
Common mistake
The search from the found example is rewritten with while, and the break with a value is kept:
fn main() {
let mut n = 1;
let found = while n < 100 {
if n * n > 50 {
break n; // ✗
}
n += 1;
};
}error[E0571]: `break` with value from a `while` loopThe program does not compile. A while loop can also end without break, when its condition becomes false, and then there would be nothing to give back. That is why only loop gives a value through break, and a search with a value is written with loop, as in the example above.
Key points
looprepeats its block untilbreakstops it;continueskips the rest of a pass.loopis an expression:break valueleaves the loop and makesvaluethe value of the wholeloop.whilechecks aboolcondition before every pass and may run zero times.breakwith a value is allowed only inloop: inwhileit is errorE0571.