Loop and break
Quick answer
loop repeats its body until control leaves the loop. break exits the innermost loop unless a label specifies another loop. A loop expression can also yield a value supplied by break value.
Make termination explicit
Use loop when the exit condition is discovered during the body. For beginner examples, ensure there is a predictable exit after a small number of iterations. Update the state that controls termination. The break value becomes the value of the loop expression.
fn main() { let mut n = 0; loop { n += 1; println!("{n}"); if n == 3 { break; } }}Expected stdout (not executed):
123The counter reaches three before the loop exits.
fn main() { let mut n = 2; let result = loop { n *= 2; if n >= 10 { break n; } }; println!("Reached: {result}");}Expected stdout (not executed):
Reached: 16The sequence 4, 8, 16 first reaches the threshold at 16.
Common mistake
An unreachable break or an unchanged stopping counter can cause an infinite loop. Do not execute an unbounded example to test that mistake.
Try it yourself
Starting at 1, double the value until it reaches at least 20. Predict the break value.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Loop and break — practice quiz
Choose one answer per question, then review the explanation.
Starting with n=1, a loop triples n then breaks when n >= 10. What is the stopping value?
What value does `let stop = loop { break 4 * 3; };` store?
Why is `let mut n = 0; loop { if n == 3 { break; } }` a bad beginner counting example?