Is there a way to have nested for
loops in Rust and break the outer one from inside the inner one, the way one could do e.g. in Java? I know Rust supports named breaks in loop
but I can't seem to find information about the same regarding for
.
The break control statement allows us to stop the execution of a loop, break out of its iteration cycle and continue on to any code after it. To use the break control statement, we simply write the break keyword where we want to break out of the loop.
In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
break only breaks you out of the innermost loop.
Set a flag which is checked by the outer loop, or set the outer loops condition. Put the loop in a function and use return to break out of all the loops at once.
Yes. It uses the same syntax as lifetimes.
fn main() { 'outer: for x in 0..5 { 'inner: for y in 0..5 { println!("{},{}", x, y); if y == 3 { break 'outer; } } } }
See loop labels documentation and the related section of the reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With