Adding docs for loops and loop labels.
This commit is contained in:
parent
a5c12f4e39
commit
b36551b0e2
2 changed files with 41 additions and 0 deletions
|
|
@ -26,6 +26,7 @@
|
|||
* [Primitive Types](primitive-types.md)
|
||||
* [Comments](comments.md)
|
||||
* [if](if.md)
|
||||
* [infinite loops](infinite-loops.md)
|
||||
* [for loops](for-loops.md)
|
||||
* [while loops](while-loops.md)
|
||||
* [Ownership](ownership.md)
|
||||
|
|
|
|||
40
src/doc/trpl/infinite-loops.md
Normal file
40
src/doc/trpl/infinite-loops.md
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
% infinite loops
|
||||
|
||||
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:
|
||||
|
||||
```
|
||||
loop {
|
||||
println!("Loop forever!");
|
||||
}
|
||||
```
|
||||
|
||||
Leaving a infinite `loop` can be achieved using a break statement as follows:
|
||||
|
||||
```
|
||||
let mut i = 0;
|
||||
loop {
|
||||
if i == 10 {
|
||||
break;
|
||||
}
|
||||
println!("Loop number {}", i);
|
||||
i = i + 1;
|
||||
}
|
||||
```
|
||||
|
||||
## Loop labels
|
||||
|
||||
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`.
|
||||
|
||||
```
|
||||
let mut i = 0;
|
||||
'outer: loop {
|
||||
'inner: loop {
|
||||
if i == 10 {
|
||||
break 'outer;
|
||||
}
|
||||
i = i + 1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In the above example, the inner `loop` is able to cause the outer `loop` to stop.
|
||||
Loading…
Add table
Add a link
Reference in a new issue