Sub topic 7
Loop labels and returning values from loops
This chapter covers two features of Rust's loops: break with a value, and loop labels. It assumes you can build and run a program with cargo, know the primitive types, and understand let and let mut. It also assumes you have read the earlier chapters on if/else, loop, while, and for.
Loops as expressions
Most Rust constructs are expressions, and loop is one of them. A loop runs until something stops it, and break can carry a value out of it. 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 loop finds the first number whose square exceeds 50. Notice the semicolon after the closing brace of the loop. It ends the let statement, not the loop.
The pattern replaces a common alternative: declaring a mutable variable before the loop, assigning to it inside, and then breaking. With break value, the binding first_big is not mutable and is assigned exactly once.
Which loops can return a value
Only loop can break with a value. The reason is that loop is the only loop that must exit through a break. A while or for loop can also end because its condition turned false or its iterator ran out. In that case there is no break to supply a value. Rust gives those loops the type ().
| Loop | Can `break` carry a value? | Type of the loop expression |
|---|---|---|
| `loop` | Yes | The type of the `break` values (or `!` if it never breaks) |
| `while` | No | `()` |
| `for` | No | `()` |
A bare break; in a loop produces (). Every break in the same loop must produce the same type, and the compiler checks this.
fn main() {
let mut n = 27u32;
let mut steps = 0;
let result = loop {
if n == 1 {
break steps;
}
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
steps += 1;
};
println!("{result}");
}This counts the steps of the Collatz sequence from 27 and prints 111. Here break steps; is the only exit, so the type of result is the type of steps, which is i32 by default.
The never type and a loop with no break
A loop with no break never finishes. Its type is !, the never type, which coerces to any other type. That is why a function can end in an infinite loop and still declare a return type.
fn serve() -> ! {
let mut tick = 0u32;
loop {
tick = tick.wrapping_add(1);
if tick == 3 {
std::process::exit(0);
}
}
}
fn main() {
serve();
}The loop here has no break, so the compiler accepts -> !. The function leaves through std::process::exit, which also returns !.
Why a value from `break` is useful
Retry and search logic often has this shape: try something until it works, and keep the result. A value-returning loop expresses that directly.
fn main() {
let data = [3, 8, 12, 5, 20];
let mut index = 0;
let found = loop {
if index == data.len() {
break None;
}
if data[index] > 10 {
break Some(index);
}
index += 1;
};
println!("{found:?}");
}This prints Some(2). Both break expressions produce an Option<usize>. None alone does not tell the compiler the full type, but Some(index) does, so inference succeeds.
In practice, an iterator method such as position is shorter for this exact search. Use a loop with break when the exit conditions are more varied than an iterator adapter can express, such as when you mutate state between attempts.
Loop labels
A break or continue normally affects the innermost loop. When loops are nested, you sometimes want to leave or skip an outer loop. A loop label names a loop so you can target it.
A label is an identifier that starts with a single quote, followed by a colon, placed directly before the loop.
fn main() {
'outer: for x in 1..10 {
for y in 1..10 {
if x * y == 42 {
println!("{x} * {y} = 42");
break 'outer;
}
}
}
}This prints 6 * 7 = 42. Without the label, break would only leave the inner for, and the outer loop would continue with the next x. With break 'outer, both loops stop at once.
`continue` with a label
continue 'label abandons the current iteration of the labeled loop and moves to its next iteration. It also abandons every inner loop that was running.
fn main() {
'rows: for row in 1..=4 {
for col in 1..=4 {
if col > row {
continue 'rows;
}
print!("{} ", row * col);
}
println!("unreachable for this input");
}
println!();
}The inner loop prints values while col <= row. When col exceeds row, continue 'rows jumps to the next row, so the println! line after the inner loop never runs for rows 1 to 3. For row 4, the inner loop finishes all four columns normally, so that line runs once. The output is 1 2 4 3 6 9 4 8 12 16 unreachable for this input followed by an empty line, all on one line apart from the final newline.
That example is deliberately odd, and it shows an edge case: code after an inner loop runs only if the inner loop ends normally.
Label rules
- A label starts with
'and is followed by an identifier, such as'outeror'search. - The label goes before
loop,while, orfor. It can also go before a plain block (see below). break 'labelandcontinue 'labelmust appear inside the labeled construct.- Labels can be shadowed by an inner label with the same name, which triggers a warning. Choose distinct names.
- Labels live in their own namespace. A label named
'xdoes not clash with a variable namedx.
Combining labels and values
A labeled loop can receive a value from break 'label value. This lets an inner loop decide the result of an outer one.
fn main() {
let grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let target = 6;
let position = 'search: loop {
let mut row = 0;
while row < grid.len() {
let mut col = 0;
while col < grid[row].len() {
if grid[row][col] == target {
break 'search Some((row, col));
}
col += 1;
}
row += 1;
}
break None;
};
println!("{position:?}");
}This prints Some((1, 2)). The inner while loops cannot carry values themselves, but break 'search reaches out to the outer loop, which can. The final break None; handles the case where the whole grid is scanned without a match.
Only a loop can be the target of break 'label value. If you label a for or while loop and try to break with a value, the compiler rejects it.
Labeled blocks
A label can also name a block. break 'label value then exits that block early and gives it a value. This is useful when you want an early exit but no looping.
fn grade(score: u32) -> &'static str {
let letter = 'pick: {
if score >= 90 {
break 'pick "A";
}
if score >= 80 {
break 'pick "B";
}
"C or lower"
};
letter
}
fn main() {
println!("{}", grade(85));
}This prints B. If no break runs, the block's final expression, "C or lower", becomes its value. Note that continue cannot target a labeled block, because a block does not repeat.
Common errors
Mismatched `break` types
Every break in a loop must have a compatible type.
fn main() {
let mut n = 0;
let value = loop {
n += 1;
if n == 3 {
break n;
}
if n == 10 {
break "too far";
}
};
println!("{value}");
}This does not compile. The first break gives an integer and the second gives a &str. Fix it by making both the same type.
Breaking with a value from `for` or `while`
Writing break 5; inside a for or while gives the error "break with value from a for loop" (or while). Switch to loop if you need the value, or set a variable before the loop and assign to it.
A missing semicolon after the loop
If you write let x = loop { ... } and omit the final semicolon, the compiler reports a syntax error at the next line. The let is a statement and needs its terminator.
Using a label outside its scope
A break 'a outside the loop labeled 'a is an error ("use of undeclared label"). Check that the break is nested inside the loop it names.
Unreachable code after an infinite loop
Code placed after a loop that has no break is unreachable, and the compiler warns about it. That warning usually points to a missing break.
Choosing between labels and alternatives
Labels solve a real problem, but they can make code harder to follow when overused. Consider these options.
- Extract a function. Put the nested loops in a function and use
returnto leave all of them. This often reads better than a label, and it gives the search a name. - Use iterator adapters. Methods like
find,position, andanyexpress many searches without explicit loops. - Use a label when the loops share local state that would be awkward to pass to a function, or when the exit logic is short and clear.
The following diagram shows how control moves in a nested loop with a labeled break and a labeled continue.
Summary
loopis an expression.break valuemakes that value the result of the loop.- Only
loopcan break with a value.whileandforhave type(). - All
breakexpressions in oneloopmust have the same type. - A label such as
'outer:letsbreakandcontinuetarget a specific enclosing loop. break 'label valuecan pass a value to a labeledloopor a labeled block.- Prefer a function with
returnor an iterator method when they make the code clearer.
Exercise
The function below should return the first pair (a, b) with 1 <= a < b <= 20 where a b equals 91, or None if no pair exists. Fill in the missing parts so it compiles and returns Some((7, 13)). Use a labeled loop and break with a value. fn find_pair() -> Option<(u32, u32)> { let result = 'search: loop { for a in 1..=20 { for b in (a + 1)..=20 { if a b == 91 { // missing } } } // missing }; result }
Show answer
Use break 'search Some((a, b)); inside the if, and break None; after the for loops: fn find_pair() -> Option<(u32, u32)> { let result = 'search: loop { for a in 1..=20 { for b in (a + 1)..=20 { if a * b == 91 { break 'search Some((a, b)); } } } break None; }; result } The for loops cannot carry a value, so the break targets the outer labeled loop. The trailing break None; runs only if no pair matched, and it ensures the loop ends with the same Option type.
Exercise
Why does let x = while n < 5 { n += 1; break n; }; fail to compile, and how do you fix it?
Show answer
A while loop has type () and cannot break with a value, because it may end when its condition becomes false, with no value to give. Replace it with loop and test the condition inside: let x = loop { if n >= 5 { break n; } n += 1; };