简体   繁体   English

具有生命周期的循环意味着什么?

[英]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: 我正在查看一些Rust代码并看到了类似的内容:

'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. 您可能还会遇到嵌套循环的情况,需要指定break或continue语句的用途。 Like most other languages, Rust's break or continue apply to the innermost loop. 像大多数其他语言一样,Rust的中断或继续应用于最内层循环。 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. 在您想要中断或继续其中一个外部循环的情况下,可以使用标签来指定break或continue语句应用于哪个循环。

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. 在下面的例子中,当x是偶数时,我们继续下一次外循环迭代,而当y是偶数时,我们继续下一次内循环迭代。 So it will execute the println! 所以它会执行println! when both x and y are odd. 当x和y都是奇数时。

'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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM