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;
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With