3 Rust also has a `while` loop. It looks like this:
6 let mut x = 5; // mut x: i32
7 let mut done = false; // mut done: bool
20 `while` loops are the correct choice when you’re not sure how many times
23 If you need an infinite loop, you may be tempted to write this:
29 However, Rust has a dedicated keyword, `loop`, to handle this case:
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
41 ## Ending iteration early
43 Let’s take a look at that `while` loop we had earlier:
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`.
64 In this case, we can write the loop in a better way with `break`:
74 if x % 5 == 0 { break; }
78 We now loop forever with `loop` and use `break` to break out early.
80 `continue` is similar, but instead of ending the loop, goes to the next
81 iteration. This will only print the odd numbers:
85 if x % 2 == 0 { continue; }
91 Both `continue` and `break` are valid in both `while` loops and [`for` loops][for].