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
.
Asked
Active
Viewed 1.6k times
57

Arets Paeglis
- 3,856
- 4
- 35
- 44
1 Answers
93
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.

Shepmaster
- 388,571
- 95
- 1,107
- 1,366

Lily Ballard
- 182,031
- 33
- 381
- 347
-
4@NoeticJun It's mentioned in the section [Infinite loops](http://static.rust-lang.org/doc/0.9/rust.html#infinite-loops) (followed by Break expressions). Although it's a bit confusing, because the example break is `break foo` instead of `break 'foo`. It also uses both "label" and "lifetime" to refer to the same thing. It should be rewritten. – Lily Ballard Apr 07 '14 at 22:10