11% while loops
22
3- The other kind of looping construct in Rust is the ` while ` loop. It looks like
4- this:
3+ Rust also has a ` while ` loop. It looks like this:
54
65``` {rust}
76let mut x = 5; // mut x: u32
87let mut done = false; // mut done: bool
98
109while !done {
1110 x += x - 3;
11+
1212 println!("{}", x);
13- if x % 5 == 0 { done = true; }
13+
14+ if x % 5 == 0 {
15+ done = true;
16+ }
1417}
1518```
1619
17- ` while ` loops are the correct choice when you' re not sure how many times
20+ ` while ` loops are the correct choice when you’ re not sure how many times
1821you need to loop.
1922
2023If you need an infinite loop, you may be tempted to write this:
2124
22- ``` { rust,ignore}
25+ ``` rust,ignore
2326while true {
2427```
2528
2629However, Rust has a dedicated keyword, ` loop ` , to handle this case:
2730
28- ``` { rust,ignore}
31+ ``` rust,ignore
2932loop {
3033```
3134
32- Rust's control-flow analysis treats this construct differently than a
33- ` while true ` , since we know that it will always loop. The details of what
34- that _ means_ aren't super important to understand at this stage, but in
35- general, the more information we can give to the compiler, the better it
36- can do with safety and code generation, so you should always prefer
37- ` loop ` when you plan to loop infinitely.
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.
3840
3941## Ending iteration early
4042
41- Let' s take a look at that ` while ` loop we had earlier:
43+ Let’ s take a look at that ` while ` loop we had earlier:
4244
43- ``` { rust}
45+ ``` rust
4446let mut x = 5 ;
4547let mut done = false ;
4648
4749while ! done {
4850 x += x - 3 ;
51+
4952 println! (" {}" , x );
50- if x % 5 == 0 { done = true; }
53+
54+ if x % 5 == 0 {
55+ done = true ;
56+ }
5157}
5258```
5359
@@ -57,12 +63,14 @@ modifying iteration: `break` and `continue`.
5763
5864In this case, we can write the loop in a better way with ` break ` :
5965
60- ``` { rust}
66+ ``` rust
6167let mut x = 5 ;
6268
6369loop {
6470 x += x - 3 ;
71+
6572 println! (" {}" , x );
73+
6674 if x % 5 == 0 { break ; }
6775}
6876```
@@ -72,12 +80,14 @@ We now loop forever with `loop` and use `break` to break out early.
7280` continue ` is similar, but instead of ending the loop, goes to the next
7381iteration. This will only print the odd numbers:
7482
75- ``` { rust}
83+ ``` rust
7684for x in 0 .. 10 {
7785 if x % 2 == 0 { continue ; }
7886
7987 println! (" {}" , x );
8088}
8189```
8290
83- Both ` continue ` and ` break ` are valid in both kinds of loops.
91+ Both ` continue ` and ` break ` are valid in both ` while ` loops and [ ` for ` loops] [ for ] .
92+
93+ [ for ] : for-loops.html
0 commit comments