Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean for loop to have a lifetime?

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;
    }
}
like image 750
Griffort Avatar asked May 23 '18 07:05

Griffort


1 Answers

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);
    }
}
like image 73
HEDMON Avatar answered Nov 20 '22 01:11

HEDMON