]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/while-loops.md
Rollup merge of #25614 - parir:patch-2, r=alexcrichton
[rust.git] / src / doc / trpl / while-loops.md
1 % while Loops
2
3 Rust also has a `while` loop. It looks like this:
4
5 ```rust
6 let mut x = 5; // mut x: i32
7 let mut done = false; // mut done: bool
8
9 while !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
21 you need to loop.
22
23 If you need an infinite loop, you may be tempted to write this:
24
25 ```rust,ignore
26 while true {
27 ```
28
29 However, Rust has a dedicated keyword, `loop`, to handle this case:
30
31 ```rust,ignore
32 loop {
33 ```
34
35 Rust’s control-flow analysis treats this construct differently than a `while
36 true`, since we know that it will always loop. In general, the more information
37 we can give to the compiler, the better it can do with safety and code
38 generation, so you should always prefer `loop` when you plan to loop
39 infinitely.
40
41 ## Ending iteration early
42
43 Let’s take a look at that `while` loop we had earlier:
44
45 ```rust
46 let mut x = 5;
47 let mut done = false;
48
49 while !done {
50     x += x - 3;
51
52     println!("{}", x);
53
54     if x % 5 == 0 {
55         done = true;
56     }
57 }
58 ```
59
60 We had to keep a dedicated `mut` boolean variable binding, `done`, to know
61 when we should exit out of the loop. Rust has two keywords to help us with
62 modifying iteration: `break` and `continue`.
63
64 In this case, we can write the loop in a better way with `break`:
65
66 ```rust
67 let mut x = 5;
68
69 loop {
70     x += x - 3;
71
72     println!("{}", x);
73
74     if x % 5 == 0 { break; }
75 }
76 ```
77
78 We 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
81 iteration. This will only print the odd numbers:
82
83 ```rust
84 for x in 0..10 {
85     if x % 2 == 0 { continue; }
86
87     println!("{}", x);
88 }
89 ```
90
91 Both `continue` and `break` are valid in both `while` loops and [`for` loops][for].
92
93 [for]: for-loops.html