about summary refs log tree commit diff
diff options
context:
space:
mode:
authorSteve Klabnik <steve@steveklabnik.com>2015-06-05 11:20:28 +0200
committerSteve Klabnik <steve@steveklabnik.com>2015-06-05 11:20:28 +0200
commit2bcb07933f0ab2276859335436b136a790adf8cd (patch)
treea4d5d48b98696d1a5d532d8b00c85139fdb3a53a
parentd95df9a3a9fe83fbe8e9d6ecdd5dcd8aec3f42e4 (diff)
parentc4f42a1ab4cf047921018d6ecabbb00ea47fc683 (diff)
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 :)
-rw-r--r--src/doc/trpl/for-loops.md42
1 files changed, 42 insertions, 0 deletions
diff --git a/src/doc/trpl/for-loops.md b/src/doc/trpl/for-loops.md
index 1e3f2fa54bc..2866cee3a1a 100644
--- a/src/doc/trpl/for-loops.md
+++ b/src/doc/trpl/for-loops.md
@@ -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:
+
+```text
+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
+# let lines = "hello\nworld".lines();
+for (linenumber, line) in lines.enumerate() {
+    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
+```