Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/doc/trpl/for-loops.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,45 @@ so our loop will print `0` through `9`, not `10`.
Rust does not have the “C-style” `for` loop on purpose. Manually controlling
each element of the loop is complicated and error prone, even for experienced C
developers.

# Enumerate

When you need to keep track of how many times you already looped, you can use the `.enumerate()` function.

## On ranges:

```rust
for (i,j) in (5..10).enumerate() {
println!("i = {} and j = {}", i, j);
}
```

Outputs:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs spaces before and after


```text
i = 0 and j = 5
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't look like Rust source code, you should probably just mark it as text. (Same for the output listing below.)

i = 1 and j = 6
i = 2 and j = 7
i = 3 and j = 8
i = 4 and j = 9
```
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

newline after this please


Don't forget to add the parentheses around the range.

## On iterators:

```rust
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs a space above

# let lines = "hello\nworld".lines();
for (linenumber, line) in lines.enumerate() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The integration tests correctly reported that lines is undefined. It would be okay if you added something like this:

# let lines = "hello\nworld".lines();

The # at the start will be removed before compiling this code but it will tell rustdoc to hide the line from the rendered output.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing :)

println!("{}: {}", linenumber, line);
}
```

Outputs:

```text
0: Content of line one
1: Content of line two
2: Content of line tree
3: Content of line four
```