8

I was looking at some Rust code and saw something along the lines of this:

'running: loop {
    // insert code here
    if(/* some condition */) {
        break 'running;
    }
}

What does it mean to "label" the loop with a lifetime? What are the benefits and differences between just doing:

loop {
    // insert code here
    if(/* some condition */) {
        break;
    }
}
Griffort
  • 1,174
  • 1
  • 10
  • 26

1 Answers1

14

Loop labels

You may also encounter situations where you have nested loops and need to specify which one your break or continue statement is for. Like most other languages, Rust's break or continue apply to the innermost loop. In a situation where you would like to break or continue for one of the outer loops, you can use labels to specify which loop the break or continue statement applies to.

In the example below, we continue to the next iteration of outer loop when x is even, while we continue to the next iteration of inner loop when y is even. So it will execute the println! when both x and y are odd.

'outer: for x in 0..10 {
    'inner: for y in 0..10 {
        if x % 2 == 0 { continue 'outer; } // Continues the loop over `x`.
        if y % 2 == 0 { continue 'inner; } // Continues the loop over `y`.
        println!("x: {}, y: {}", x, y);
    }
}
HEDMON
  • 727
  • 10
  • 24
  • 5
    Ahhh, makes sense. Is there a specific reason the language designers chose to go with the same syntax of lifetimes? Seems unnecessarily confusing. :/ – Griffort May 23 '18 at 07:26
  • 8
    @Griffort: Probably in part because (with the exception of `'static`), lifetimes can be thought of as scope labels. They're often tied in some way to actual lexical scopes, and nest just like scopes do. It also avoids any possible overlap or conflict with type ascription syntax; the two would have been disjoint, but might have been a little visually confusing. – DK. May 23 '18 at 08:01