Gri*_*ort 5 loops break lifetime rust
我正在查看一些Rust代码并看到了类似的内容:
'running: loop {
// insert code here
if(/* some condition */) {
break 'running;
}
}
Run Code Online (Sandbox Code Playgroud)
用生命周期"标记"循环是什么意思?这样做有什么好处和不同之处:
loop {
// insert code here
if(/* some condition */) {
break;
}
}
Run Code Online (Sandbox Code Playgroud)
您可能还会遇到嵌套循环的情况,需要指定break或continue语句的用途.像大多数其他语言一样,Rust的中断或继续应用于最内层循环.在您想要中断或继续其中一个外部循环的情况下,可以使用标签来指定break或continue语句应用于哪个循环.
在下面的例子中,当x是偶数时,我们继续下一次外循环迭代,而当y是偶数时,我们继续下一次内循环迭代.所以它会执行println!当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);
}
}
Run Code Online (Sandbox Code Playgroud)