]> git.proxmox.com Git - rustc.git/blame - src/doc/trpl/while-loops.md
Imported Upstream version 1.2.0+dfsg1
[rustc.git] / src / doc / trpl / while-loops.md
CommitLineData
bd371182 1% while Loops
9346a6ac
AL
2
3Rust also has a `while` loop. It looks like this:
4
62682a34 5```rust
d9579d0f 6let mut x = 5; // mut x: i32
9346a6ac
AL
7let mut done = false; // mut done: bool
8
9while !done {
10 x += x - 3;
11
12 println!("{}", x);
13
14 if x % 5 == 0 {
15 done = true;
16 }
17}
18```
19
20`while` loops are the correct choice when you’re not sure how many times
21you need to loop.
22
23If you need an infinite loop, you may be tempted to write this:
24
25```rust,ignore
26while true {
27```
28
29However, Rust has a dedicated keyword, `loop`, to handle this case:
30
31```rust,ignore
32loop {
33```
34
35Rust’s control-flow analysis treats this construct differently than a `while
36true`, since we know that it will always loop. In general, the more information
37we can give to the compiler, the better it can do with safety and code
38generation, so you should always prefer `loop` when you plan to loop
39infinitely.
40
41## Ending iteration early
42
43Let’s take a look at that `while` loop we had earlier:
44
45```rust
46let mut x = 5;
47let mut done = false;
48
49while !done {
50 x += x - 3;
51
52 println!("{}", x);
53
54 if x % 5 == 0 {
55 done = true;
56 }
57}
58```
59
60We had to keep a dedicated `mut` boolean variable binding, `done`, to know
61when we should exit out of the loop. Rust has two keywords to help us with
62modifying iteration: `break` and `continue`.
63
64In this case, we can write the loop in a better way with `break`:
65
66```rust
67let mut x = 5;
68
69loop {
70 x += x - 3;
71
72 println!("{}", x);
73
74 if x % 5 == 0 { break; }
75}
76```
77
78We now loop forever with `loop` and use `break` to break out early.
79
80`continue` is similar, but instead of ending the loop, goes to the next
81iteration. This will only print the odd numbers:
82
83```rust
84for x in 0..10 {
85 if x % 2 == 0 { continue; }
86
87 println!("{}", x);
88}
89```
90
91Both `continue` and `break` are valid in both `while` loops and [`for` loops][for].
92
93[for]: for-loops.html