We can return a value from loops with break
, for example:
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}");
}
And we can break the outer loops using labels, but is there a way to also return a value while breaking outer loops?
fn main() {
let mut count = 0;
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up; // <-- Want to retun a value here
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}");
}
break 'counting_up 42;
and assign likelet foo = 'counting_up: loop { ... }...
. Is that what you mean? – Electrum