Skip to content

Commit b36551b

Browse files
committed
Adding docs for loops and loop labels.
1 parent a5c12f4 commit b36551b

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/doc/trpl/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
* [Primitive Types](primitive-types.md)
2727
* [Comments](comments.md)
2828
* [if](if.md)
29+
* [infinite loops](infinite-loops.md)
2930
* [for loops](for-loops.md)
3031
* [while loops](while-loops.md)
3132
* [Ownership](ownership.md)

src/doc/trpl/infinite-loops.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
% infinite loops
2+
3+
The infinite `loop` is the simplest form of `loop` available in Rust. Using the keyword `loop`, Rust provides a way to loop until a `break` or `return` is issued. Rust's infinite `loop`s look like this:
4+
5+
```
6+
loop {
7+
println!("Loop forever!");
8+
}
9+
```
10+
11+
Leaving a infinite `loop` can be achieved using a break statement as follows:
12+
13+
```
14+
let mut i = 0;
15+
loop {
16+
if i == 10 {
17+
break;
18+
}
19+
println!("Loop number {}", i);
20+
i = i + 1;
21+
}
22+
```
23+
24+
## Loop labels
25+
26+
Labels can be assigned to `loop`s to so that, in the case of nested `loop`s, an outer `loop` may be left early when certain criteria are met in an inner `loop`.
27+
28+
```
29+
let mut i = 0;
30+
'outer: loop {
31+
'inner: loop {
32+
if i == 10 {
33+
break 'outer;
34+
}
35+
i = i + 1;
36+
}
37+
}
38+
```
39+
40+
In the above example, the inner `loop` is able to cause the outer `loop` to stop.

0 commit comments

Comments
 (0)