Skip to content

Commit 2bcb079

Browse files
committed
Rollup merge of #25925 - azerupi:patch-4, r=steveklabnik
Hi I added a little section in the for loops about the `enumerate()` function. I think it's useful for beginners to know this function and how you can use it. I used the title loopcounter, but it's probably not the best word to describe it. So let me know if there is a better word :)
2 parents d95df9a + c4f42a1 commit 2bcb079

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/doc/trpl/for-loops.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,45 @@ 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+
# Enumerate
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+
57+
Outputs:
58+
59+
```text
60+
i = 0 and j = 5
61+
i = 1 and j = 6
62+
i = 2 and j = 7
63+
i = 3 and j = 8
64+
i = 4 and j = 9
65+
```
66+
67+
Don't forget to add the parentheses around the range.
68+
69+
## On iterators:
70+
71+
```rust
72+
# let lines = "hello\nworld".lines();
73+
for (linenumber, line) in lines.enumerate() {
74+
println!("{}: {}", linenumber, line);
75+
}
76+
```
77+
78+
Outputs:
79+
80+
```text
81+
0: Content of line one
82+
1: Content of line two
83+
2: Content of line tree
84+
3: Content of line four
85+
```

0 commit comments

Comments
 (0)