Sub topic 7
Loop labels and returning values from loops
This chapter assumes you can build and run a Rust program with cargo, know let and let mut, and have used loop, while, and for. You will learn two features of break: returning a value from a loop, and exiting an outer loop with a label.
Why `loop` can produce a value
In Rust, loop is an expression. An infinite loop only ends when you break, so break can carry a value. That value becomes the value of the whole loop expression.
fn main() {
let mut count = 0;
let first_big = loop {
count += 1;
if count * count > 50 {
break count;
}
};
println!("{first_big}");
for i in (1..=3).rev() {
println!("{i}");
}
}This prints 8, then 3, 2, 1. The first square above 50 is 64, from count equal to 8. The loop is the right side of let first_big = ...;, so the break count; supplies the value to store.
The for loop at the end shows an inclusive range, 1..=3, reversed with .rev(). A for loop has no value to return, so break inside it can't carry one.
Which loops can return a value
Only loop can use break value. The compiler knows a loop can't finish without hitting a break. A while or for loop can also end because its condition fails or its iterator runs out. In that case there would be no value to return.
| Loop kind | `break` with a value | Type of the loop expression |
|---|---|---|
| `loop` | Allowed | The type of the `break` values |
| `while` | Not allowed | `()` |
| `for` | Not allowed | `()` |
If a loop has several break statements, every one must give a value of the same type. A bare break; gives (), so you can't mix it with break 5;.
Labels for nested loops
A plain break leaves only the innermost loop. To leave an outer loop, give it a label. A label is a name that starts with a single quote, written before the loop and followed by a colon.
fn main() {
'outer: for x in 1..10 {
for y in 1..10 {
if x * y == 42 {
println!("{x} * {y} = 42");
break 'outer;
}
}
}
}The first pair found is x = 5, y = 9? No. The outer loop starts with x = 1 and works upward, so it checks x = 6, y = 7 first. The program prints 6 * 7 = 42 and stops. Without the label, break would only end the inner loop, and the outer loop would keep going.
continue accepts a label too. continue 'outer; skips the rest of the current inner loop and moves the outer loop to its next iteration.
How the control flow moves
The diagram below shows the search above.
Combining labels and values
A label can also be attached to a loop so you can return a value from an outer loop. Write break 'label value;.
fn main() {
let mut x = 0;
let found = 'search: loop {
x += 1;
let mut y = 0;
loop {
y += 1;
if x * y == 42 && x > 3 {
break 'search (x, y);
}
if y > 10 {
break;
}
}
};
println!("{found:?}");
}This prints (6, 7). The inner break; ends only the inner loop, and its type is (). The break 'search (x, y); ends the outer loop and gives the tuple as its value. Each loop checks its own break types separately.
Common errors
- Writing
break valueinside awhileorforloop gives a compile error, because those loops can't return values. - Writing
break 'outer;with no matching label in scope gives an "undeclared label" error. - Forgetting the semicolon after the closing brace of
let x = loop { ... };is a syntax error, because theletstatement needs one. - Mixing
break;andbreak 5;in the sameloopgives a type mismatch.
Exercise
What does this program print, and why? let r = 'a: loop { let mut n = 0; loop { n += 3; if n > 10 { break 'a n; } } }; followed by println!("{r}");
Show answer
It prints 12. The inner loop adds 3 each time: 3, 6, 9, 12. When n becomes 12, which is above 10, break 'a n; leaves the outer loop labeled 'a and gives n as its value, so r is 12.