-
Notifications
You must be signed in to change notification settings - Fork 12.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rustdoc: Add loopcounter (enumerate) section to the for-loop chapter #25925
Changes from 3 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -41,3 +41,44 @@ 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: | ||
|
||
```text | ||
i = 0 and j = 5 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
i = 1 and j = 6 | ||
i = 2 and j = 7 | ||
i = 3 and j = 8 | ||
i = 4 and j = 9 | ||
``` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. needs a space above |
||
for (linenumber, line) in lines.enumerate() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The integration tests correctly reported that # let lines = "hello\nworld".lines(); The There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
``` |
There was a problem hiding this comment.
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