expression

Rust Return a result from a loop

A `loop` can finish with a value supplied by `break`. Use this when a repeated calculation stops once a condition is met. Expected output (not executed): 16 Why: The sequence reaches 2, 4, 8 and then 16. Common mistake: Ordinary `while` and `for` loops do not support breaking from that loop with a value.

Formal Syntax & Structure

rust syntaxrust
loop { ... break value; }

Working Example

Example Snippetrust
fn main() {    let mut count = 1;    let found = loop {        count *= 2;        if count >= 10 { break count; }    };    println!("{found}");}
Rust Reference