keyword

Rust loop: repeat until explicitly stopped

Use `loop` for repetition without a condition at the top. It continues until control leaves it, for example through break or return. A break expression can also supply the result of an ordinary loop. Expected output: 3 Why: On the third iteration, break leaves the loop and supplies the number. Common mistake: A loop with no reachable exit can run forever.

Formal Syntax & Structure

rust syntaxrust
loop { statements; break; }

Working Example

Example Snippetrust
fn main() {    let mut attempts = 0;    let result = loop {        attempts += 1;        if attempts == 3 {            break attempts;        }    };    println!("{result}");}
Rust Reference