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}");
}
>Solution :
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}");
}