Skip to content

Commit 6e2f18e

Browse files
committed
Add loopcounter section to the for-loop chapter
Sometimes loop counters are useful and we should show new users how it is achieved in Rust.
1 parent 243e85f commit 6e2f18e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/doc/trpl/for-loops.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,38 @@ so our loop will print `0` through `9`, not `10`.
4141
Rust does not have the “C-style” `for` loop on purpose. Manually controlling
4242
each element of the loop is complicated and error prone, even for experienced C
4343
developers.
44+
45+
# Loopcounter
46+
47+
When 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
52+
for (i,j) in (5..10).enumerate() {
53+
println!("i = {} and j = {}", i, j);
54+
}
55+
```
56+
Outputs:
57+
```
58+
i = 0 and j = 5
59+
i = 1 and j = 6
60+
i = 2 and j = 7
61+
i = 3 and j = 8
62+
i = 4 and j = 9
63+
```
64+
Don't forget to add the parentheses around the range.
65+
66+
#### On iterators:
67+
```rust
68+
for (linenumber, line) in lines.enumerate() {
69+
println!("{}: {}", linenumber, line);
70+
}
71+
```
72+
Outputs:
73+
```
74+
0: Content of line one
75+
1: Content of line two
76+
2: Content of line tree
77+
3: Content of line four
78+
```

0 commit comments

Comments
 (0)