3 Looping is the last basic construct that we haven't learned yet in Rust. Rust has
4 two main looping constructs: `for` and `while`.
8 The `for` loop is used to loop a particular number of times. Rust's `for` loops
9 work a bit differently than in other systems languages, however. Rust's `for`
10 loop doesn't look like this "C-style" `for` loop:
13 for (x = 0; x < 10; x++) {
18 Instead, it looks like this:
22 println!("{}", x); // x: i32
26 In slightly more abstract terms,
29 for var in expression {
34 The expression is an iterator, which we will discuss in more depth later in the
35 guide. The iterator gives back a series of elements. Each element is one
36 iteration of the loop. That value is then bound to the name `var`, which is
37 valid for the loop body. Once the body is over, the next value is fetched from
38 the iterator, and we loop another time. When there are no more values, the
41 In our example, `0..10` is an expression that takes a start and an end position,
42 and gives an iterator over those values. The upper bound is exclusive, though,
43 so our loop will print `0` through `9`, not `10`.
45 Rust does not have the "C-style" `for` loop on purpose. Manually controlling
46 each element of the loop is complicated and error prone, even for experienced C
49 We'll talk more about `for` when we cover *iterators*, later in the Guide.
53 The other kind of looping construct in Rust is the `while` loop. It looks like
57 let mut x = 5; // mut x: u32
58 let mut done = false; // mut done: bool
63 if x % 5 == 0 { done = true; }
67 `while` loops are the correct choice when you're not sure how many times
70 If you need an infinite loop, you may be tempted to write this:
76 However, Rust has a dedicated keyword, `loop`, to handle this case:
82 Rust's control-flow analysis treats this construct differently than a
83 `while true`, since we know that it will always loop. The details of what
84 that _means_ aren't super important to understand at this stage, but in
85 general, the more information we can give to the compiler, the better it
86 can do with safety and code generation, so you should always prefer
87 `loop` when you plan to loop infinitely.
89 ## Ending iteration early
91 Let's take a look at that `while` loop we had earlier:
100 if x % 5 == 0 { done = true; }
104 We had to keep a dedicated `mut` boolean variable binding, `done`, to know
105 when we should exit out of the loop. Rust has two keywords to help us with
106 modifying iteration: `break` and `continue`.
108 In this case, we can write the loop in a better way with `break`:
116 if x % 5 == 0 { break; }
120 We now loop forever with `loop` and use `break` to break out early.
122 `continue` is similar, but instead of ending the loop, goes to the next
123 iteration. This will only print the odd numbers:
127 if x % 2 == 0 { continue; }
133 Both `continue` and `break` are valid in both kinds of loops.