Labels
Both continue
and break
can optionally take a label argument which is used
to break out of nested loops:
fn without_labeled_loops() { let mut break_outer_loop = false; for i in [1, 2, 3] { for j in [11, 22, 33] { println!("{i}, {j}"); if i + j == 24 { break_outer_loop = true; break; } } if break_outer_loop { break; } } } fn with_labeled_loops() { 'outer: for i in [1, 2, 3] { for j in [11, 22, 33] { println!("{i}, {j}"); if i + j == 24 { break 'outer; } } } } fn main() { without_labeled_loops(); println!("-----"); with_labeled_loops(); }
- Note that
loop
is the only looping construct which returns a non-trivial value. This is because itβs guaranteed to be entered at least once (unlikewhile
andfor
loops).