Labels

Both continue and break can optionally take a label argument which is used to break out of nested loops:

  1. fn main() {
  2.     let s = [[5, 6, 7], [8, 9, 10], [21, 15, 32]];
  3.     let mut elements_searched = 0;
  4.     let target_value = 10;
  5.     'outer: for i in 0..=2 {
  6.         for j in 0..=2 {
  7.             elements_searched += 1;
  8.             if s[i][j] == target_value {
  9.                 break 'outer;
  10.             }
  11.         }
  12.     }
  13.     print!("elements searched: {elements_searched}");
  14. }
  • Labeled break also works on arbitrary blocks, e.g.

    1. #![allow(unused)]
    2. fn main() {
    3. 'label: {
    4.     break 'label;
    5.     println!("This line gets skipped");
    6. }
    7. }