]> git.proxmox.com Git - rustc.git/blame - src/doc/trpl/for-loops.md
Imported Upstream version 1.2.0+dfsg1
[rustc.git] / src / doc / trpl / for-loops.md
CommitLineData
9346a6ac
AL
1% for Loops
2
3The `for` loop is used to loop a particular number of times. Rust’s `for` loops
4work a bit differently than in other systems languages, however. Rust’s `for`
5loop doesn’t look like this “C-style” `for` loop:
6
7```c
8for (x = 0; x < 10; x++) {
9 printf( "%d\n", x );
10}
11```
12
13Instead, it looks like this:
14
15```rust
16for x in 0..10 {
17 println!("{}", x); // x: i32
18}
19```
20
21In slightly more abstract terms,
22
23```ignore
24for var in expression {
25 code
26}
27```
28
29The expression is an [iterator][iterator]. The iterator gives back a series of
30elements. Each element is one iteration of the loop. That value is then bound
31to the name `var`, which is valid for the loop body. Once the body is over, the
32next value is fetched from the iterator, and we loop another time. When there
33are no more values, the `for` loop is over.
34
35[iterator]: iterators.html
36
37In our example, `0..10` is an expression that takes a start and an end position,
38and gives an iterator over those values. The upper bound is exclusive, though,
39so our loop will print `0` through `9`, not `10`.
40
41Rust does not have the “C-style” `for` loop on purpose. Manually controlling
42each element of the loop is complicated and error prone, even for experienced C
43developers.
62682a34
SL
44
45# Enumerate
46
47When you need to keep track of how many times you already looped, you can use the `.enumerate()` function.
48
49## On ranges:
50
51```rust
52for (i,j) in (5..10).enumerate() {
53 println!("i = {} and j = {}", i, j);
54}
55```
56
57Outputs:
58
59```text
60i = 0 and j = 5
61i = 1 and j = 6
62i = 2 and j = 7
63i = 3 and j = 8
64i = 4 and j = 9
65```
66
67Don't forget to add the parentheses around the range.
68
69## On iterators:
70
71```rust
72# let lines = "hello\nworld".lines();
73for (linenumber, line) in lines.enumerate() {
74 println!("{}: {}", linenumber, line);
75}
76```
77
78Outputs:
79
80```text
810: Content of line one
821: Content of line two
832: Content of line tree
843: Content of line four
85```