Skip to content

Commit e490ba9

Browse files
committed
Rollup merge of rust-lang#27177 - echochamber:master, r=steveklabnik
Was browsing somebody else's code and came across a snippet using labels. Looking around, it seems like there was an example for this in [rustbyexample](http://rustbyexample.com/flow_control/loop/nested.html) but none in trpl.
2 parents 3fa9090 + c80bff0 commit e490ba9

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/doc/trpl/while-loops.md

+18
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,24 @@ for x in 0..10 {
8888
}
8989
```
9090

91+
You may also encounter situations where you have nested loops and need to
92+
specify which one your `break` or `continue` statement is for. Like most
93+
other languages, by default a `break` or `continue` will apply to innermost
94+
loop. In a sitation where you would like to a `break` or `continue` for one
95+
of the outer loops, you can use labels to specify which loop the `break` or
96+
`continue` statement applies to. This will only print when both `x` and `y` are
97+
odd:
98+
99+
```rust
100+
'outer: for x in 0..10 {
101+
'inner: for y in 0..10 {
102+
if x % 2 == 0 { continue 'outer; } // continues the loop over x
103+
if y % 2 == 0 { continue 'inner; } // continues the loop over y
104+
println!("x: {}, y: {}", x, y);
105+
}
106+
}
107+
```
108+
91109
Both `continue` and `break` are valid in both `while` loops and [`for` loops][for].
92110

93111
[for]: for-loops.html

0 commit comments

Comments
 (0)