about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorMathieu David <mathieudavid@mathieudavid.org>2015-05-31 14:03:57 +0200
committerMathieu David <mathieudavid@mathieudavid.org>2015-05-31 14:03:57 +0200
commit6e2f18ef322c094ed49eee11994fc49c5cacbc2a (patch)
tree665dbe929097c99dd1bf274f0ca61b4a8345ed99 /src
parent243e85f393a9e4527d814ecc9dfe23d2e3f9c737 (diff)
downloadrust-6e2f18ef322c094ed49eee11994fc49c5cacbc2a.tar.gz
rust-6e2f18ef322c094ed49eee11994fc49c5cacbc2a.zip
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.
Diffstat (limited to 'src')
-rw-r--r--src/doc/trpl/for-loops.md35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/doc/trpl/for-loops.md b/src/doc/trpl/for-loops.md
index 1e3f2fa54bc..c8422f351d1 100644
--- a/src/doc/trpl/for-loops.md
+++ b/src/doc/trpl/for-loops.md
@@ -41,3 +41,38 @@ 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.
+
+# Loopcounter
+
+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:
+```
+i = 0 and j = 5
+i = 1 and j = 6
+i = 2 and j = 7
+i = 3 and j = 8
+i = 4 and j = 9
+```
+Don't forget to add the parentheses around the range.
+
+#### On iterators: 
+```rust
+for (linenumber, line) in lines.enumerate() {
+    println!("{}: {}", linenumber, line);
+}
+```
+Outputs:
+```
+0: Content of line one
+1: Content of line two
+2: Content of line tree
+3: Content of line four
+```