Rust Break and Continue
break and continue let you interrupt a loop early instead of always running it to the end.
break — exit the loop entirely
Section titled “break — exit the loop entirely”break stops the loop immediately, and execution jumps to whatever comes right after it:
fn main() { for i in 1..=10 { if i == 5 { break; } println!("{i}"); }}Output:
1234Even though the range goes up to 10, the loop stops the moment i hits 5.
continue — skip to the next round
Section titled “continue — skip to the next round”continue skips the rest of the current pass and jumps straight to the next one, rather than stopping the loop altogether:
fn main() { for i in 1..=10 { if i % 2 == 0 { continue; // skip even numbers } println!("{i}"); }}Output:
13579Every even number gets skipped — continue fires, and the loop moves straight to the next value of i without running println!.
Labeled loops
Section titled “Labeled loops”When you nest one loop inside another, plain break/continue only affects the innermost loop. If you need to break out of an outer loop from inside a nested one, give the outer loop a label (written as 'name:):
fn main() { 'outer: for x in 1..=3 { for y in 1..=3 { if x * y > 4 { break 'outer; } println!("{x} x {y} = {}", x * y); } }}Output:
1 x 1 = 11 x 2 = 21 x 3 = 32 x 1 = 22 x 2 = 4Without the label, break would only stop the inner y loop, and x would keep going. break 'outer; stops both at once. continue 'outer; works the same way, if you want to skip to the outer loop’s next round instead of stopping entirely.
breakexits the loop immediately.continueskips the rest of the current iteration and moves to the next one.- A label (
'outer:) letsbreak/continuetarget an outer loop from inside a nested one.