Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named breaks in for loops in Rust

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.

like image 871
Arets Paeglis Avatar asked Apr 07 '14 07:04

Arets Paeglis


People also ask

How do you break a loop in Rust?

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.

Does Break Break all for loops?

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.

Does break () break out of innermost for loop?

break only breaks you out of the innermost loop.

How do you break every 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.


1 Answers

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.

like image 165
Lily Ballard Avatar answered Oct 23 '22 04:10

Lily Ballard