英文:
Break out of specific loop and return a value
问题
我刚开始学习Rust,到达控制流部分时,我读到break
可以返回一个值(循环是一个表达式),它还可以通过标签来退出特定的循环,例如break 'counting_up
。所以我的问题是:
是否可以将这两者结合起来?也就是说,是否可以通过为循环命名来退出特定的循环 并且 返回一个值?
如果可以,那么如何分配和声明循环的语法是什么?
break
的语法是什么?
以下是两种可能性,但都不是合法的语法:
fn main() {
let mut count = 0;
// 这样行吗?
let result = 'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
// break count*10, 'counting_up;
// 还是应该是:
break 'counting_up, count*10;
}
remaining -= 1;
}
count += 1;
};
println!("End count = {count}");
}
英文:
I have just started studying Rust and reaching the control flow section I read break
can return a value (the loop is an expression) and it can also break out of a specific loop using a label, e.g. break 'counting_up
.
So my question is:
Is it possible to combine the two? i.e. break out of a specific loop by naming it and return a value as well?
If so, what is the syntax for assigning + declaring the loop?
What is the syntax of the break
?
The following are two possibilities, but neither syntax compiles:
fn main() {
let mut count = 0;
// would this do?
let result = 'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
// break count*10, 'counting_up;
// or should it be:
break 'counting_up, count*10;
}
remaining -= 1;
}
count += 1;
};
println!("End count = {count}");
}
答案1
得分: 8
是的,确实如此,没有分隔符,只是 break 'label value
:
英文:
Yes it is, and there is no separator, just break 'label value
:
fn main() {
let mut count = 0;
let result = 'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up count*10;
}
remaining -= 1;
}
count += 1;
};
println!("End count = {count}");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论