In Rust, how does `let result = loop { ... break outcome; };` yield a value, and why can't `while` or `for` do the same?
answer
- loop is an expression too
- break can carry an operand
- the exit path without break
- E0571 on while and for
basics
~20 sA Rust loop evaluates to the operand of the break that ends it, so break outcome hands outcome to the let. A while or for loop can end without any break, so it always evaluates to (), and a valued break inside it is E0571.
solid answer
~50 s`loop` repeats its body until a `break`, and `break expr` makes `expr` the value of the whole `loop` expression, so `let result = loop { ... break outcome; };` binds whatever the exiting iteration produced. Every `break` in that loop must carry a value of one type, or rustc reports E0308. `while` and `for` are different: they can end because their condition turned false or their iterator ran out, and on that path there is no value to produce, so both always evaluate to `()`. Writing `break attempt;` inside them is E0571, `` `break` with value from a `while` loop ``. For a retry, use `loop`, increment an attempt counter, and `break` with the success or with the last error once the cap is reached; use `for` when you iterate a known range or collection.
code
rust · 22 lines#[derive(Debug)]
enum FetchError {
Timeout,
}
fn fetch(attempt: u32) -> Result<String, FetchError> {
if attempt < 3 { Err(FetchError::Timeout) } else { Ok(format!("index v{attempt}")) }
}
fn main() {
let max_attempts = 5;
let mut attempt = 0;
// `loop` is an expression: its value is what `break` carries.
let result = loop {
attempt += 1;
let outcome = fetch(attempt);
if outcome.is_ok() || attempt == max_attempts {
break outcome;
}
};
println!("{result:?} after {attempt} attempts");
}go deeper
Write let x = loop { ... break value; }; from memory and say that while and for evaluate to unit.
Explain why: while and for can finish without a break, so they have no value for that path, and name E0571 for a valued break there.
Show bounded retries that break with the final Result, the never type of a break-less loop, and ranges that avoid off-by-one indexing.
Set the team expectation that every retry loop has a visible cap and preserves its last error, so a review can see how it terminates.
## Three loops, three ways to stop Rust has three loop expressions, plus labeled blocks, which the material on labels covers. They differ in **what ends them**, and that decides whether they can produce a value. | Loop | Ends when | Value of the loop | Typical use | |---|---|---|---| | `loop { ... }` | a `break` runs (or `return`, or a panic) | the `break` operand; `!` if there is no `break` | retries, event loops, search until found | | `while cond { ... }` | `cond` is false before an iteration, or a `break` | always `()` | repeat while a condition holds | | `for pat in expr { ... }` | the iterator returns `None`, or a `break` | always `()` | walk a range or a collection | The Reference sums it up: *only `loop` and labeled block expressions support evaluation to non-trivial values.* ## `break` carries the value Inside a `loop`, `break expr` stops the loop and makes `expr` the loop's value: - **The loop's type is the common type of every `break` operand.** One `break n` and one `break "gave up"` in the same loop give E0308, *mismatched types*, with the first `break` labelled *expected because of this `break`*. - **A plain `break` means `break ()`**, so a `loop` exited only with plain `break` has type `()`. - **A `loop` with no `break` at all never finishes normally** and has the never type `!`; that is why `fn serve() -> ! { loop { handle_next(); } }` type-checks. The material on diverging expressions covers `!`. - **`return` is not `break`**: `break` leaves the innermost loop (or a labeled one) and gives the loop its value, while `return` leaves the whole function. ## Why `while` and `for` evaluate to `()` A `while` loop can stop because its condition becomes false, and a `for` loop because its iterator is exhausted. Neither path runs a `break`, so there is no operand to use as the value. Rather than invent one, Rust gives both loops the type `()` and rejects `break value` inside them: ```plaintext error[E0571]: `break` with value from a `while` loop ``` The error index says `break` *can take an argument ... in `loop` loops, but not `for`, `while`, or `while let` loops*, and rustc's help suggests a plain `break`. To get a value from a search over a range, either use `loop` with your own counter, record the result in an `Option` declared before a `for`, or use an iterator method such as `find`, which the iterators material covers. ## `for` over ranges `for` takes anything that implements `IntoIterator`; ranges are the common case: 1. `0..n` yields `0` up to `n - 1`; the end is excluded, so `for i in 0..v.len()` never indexes past the end. 2. `0..=n` includes `n`; `for _ in 0..=u8::MAX` runs 256 times without overflowing. 3. `(0..n).rev()` counts down from `n - 1` to `0`. 4. `(0..10).step_by(3)` yields `0, 3, 6, 9`; `step_by(0)` panics. 5. `5..0` is simply empty: the body never runs and nothing panics. Looping over a `Vec` by value consumes it, and choosing between `iter()`, `iter_mut()` and `into_iter()` is the iterators material's subject. ## The retry pattern A bounded retry is the textbook use of a value-producing `loop`: 1. Declare `let mut attempt = 0;` before the loop. 2. In the body, increment `attempt` and try the operation. 3. `break` with the outcome when it succeeded **or** when `attempt` reached the cap, so the loop always ends. 4. Bind the loop: `let result = loop { ... };`, with `result` typed as the operation's `Result`. Breaking with the `Result` itself keeps the last error for the caller instead of discarding it. Compare the alternatives: - **`for attempt in 1..=max` with an `Option` declared outside** works, but the loop cannot hand back the outcome, so you need a mutable placeholder and an `unwrap` or `expect` after it. - **A `while !done` flag** spreads the exit condition over two places and is easy to leave stale. - **`loop` with `break outcome`** keeps the exit and the value together, and the compiler checks that every `break` produces the same type. Adding a delay between attempts, or giving up after a deadline, changes the body but not the shape. Without a cap, the loop's termination depends on the remote side, which is a design question rather than a Rust one.
- In Rust, what is the type of a `loop` that contains no `break`?The never type `!`: such a loop can only be left by `return`, a panic or the process ending, so it never produces a value. That is why a function declared `-> !` may end in `loop { ... }`, and why the loop fits any expected type.
- Inside a Rust loop in a function, how do `break` and `return` differ?`break` leaves the innermost loop, or the labeled one, and execution continues after it; with an operand it sets the `loop`'s value. `return` leaves the whole function with the function's return value, whatever loops it is nested in.
- How do you count down from 10 to 1 in steps of 3 with a Rust `for` loop?`for i in (1..=10).rev().step_by(3)` yields `10, 7, 4, 1`: the inclusive range includes 10, `rev()` walks it from the top, and `step_by(3)` takes every third element starting with the first.
- while and for can return a value with break just like loop
- a loop needs a trailing expression after its body to produce a value
- different break statements in one loop may carry values of different types
- 0..n includes n, so iterating 0..len indexes one past the end
- a retry loop should discard the last error and break with a plain break