Breaking with a Value
break hand back a result, so the loop itself becomes the answer to a question.In this page:
let name = loop {
// body
if condition {
break value;
}
};
Returning a Value on Break
When a loop is exited using break some_value;, that value becomes the result of the entire loop expression, which can then be stored in a variable.
Example: Returning a Value on Break
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `counter`, initialized to `0`
let mut counter = 0;
// Declare an immutable variable `result`; its value comes from the block below
let result = loop {
counter += 1;
// Check whether `counter == 10`
if counter == 10 {
break counter;
}
};
// Print "Loop returned: {}" to the console, substituting in `result` (with a trailing newline)
println!("Loop returned: {}", result);
}
Login to try C/C++/Java/PHP code in the editor
Multiple break Points
A single loop can contain more than one break statement along different code paths, as long as every one of them produces a value of the same type.
Example: Multiple break Points
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `n`, initialized to `1`
let mut n = 1;
// Declare an immutable variable `outcome`; its value comes from the block below
let outcome = loop {
n *= 2;
// Check whether `n > 100`
if n > 100 {
break "too big";
}
// Check whether `n == 64`
if n == 64 {
break "found sixty-four";
}
};
// Print "{}" to the console, substituting in `outcome` (with a trailing newline)
println!("{}", outcome);
}
Login to try C/C++/Java/PHP code in the editor
Why Only loop Supports This
while and for loops can also end because their condition became false or the iterator was exhausted, so there is no single guaranteed exit value to return. loop has no implicit exit, so break value is unambiguous.
Example: Why Only loop Supports This
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `target`, set to `5`
let target = 5;
// Declare a mutable variable `current`, initialized to `0`
let mut current = 0;
// Declare an immutable variable `found_at`; its value comes from the block below
let found_at = loop {
current += 1;
// Check whether `current == target`
if current == target {
break current;
}
};
// Print "Found target at iteration {}" to the console, substituting in `found_at` (with a trailing newline)
println!("Found target at iteration {}", found_at);
}
Login to try C/C++/Java/PHP code in the editor
Combining with match on the Result
Because break value produces an ordinary value, you can immediately use it with other expressions, such as feeding it directly into a match.
Example: Combining with match on the Result
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `i`, initialized to `0`
let mut i = 0;
// Declare an immutable variable `parity`; its value comes from the block below
let parity = loop {
i += 3;
// Check whether `i > 10`
if i > 10 {
break i % 2;
}
};
// Match on `parity` and branch by pattern
match parity {
0 => println!("Ended on an even number"),
_ => println!("Ended on an odd number"),
}
}
Login to try C/C++/Java/PHP code in the editor
- Trying to use
break value;inside afororwhileloop -- onlyloopcan return a value this way. - Forgetting a semicolon after a
loopexpression when assigning its result, since the wholeloop {}is treated as one expression. - Mismatching the types produced by different
breakstatements within the sameloop, which fails to compile.
break value;only works insideloop, because onlyloopis guaranteed to be exited exclusively viabreak.- The value passed to
breakbecomes the value of the entireloopexpression. - All
breakstatements within the sameloopmust produce values of the same type. - This pattern is common for retry-until-success logic where the result is only known once the loop ends.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: