File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -41,3 +41,38 @@ so our loop will print `0` through `9`, not `10`.
41
41
Rust does not have the “C-style” ` for ` loop on purpose. Manually controlling
42
42
each element of the loop is complicated and error prone, even for experienced C
43
43
developers.
44
+
45
+ # Loopcounter
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
+ Outputs:
57
+ ```
58
+ i = 0 and j = 5
59
+ i = 1 and j = 6
60
+ i = 2 and j = 7
61
+ i = 3 and j = 8
62
+ i = 4 and j = 9
63
+ ```
64
+ Don't forget to add the parentheses around the range.
65
+
66
+ #### On iterators:
67
+ ``` rust
68
+ for (linenumber , line ) in lines . enumerate () {
69
+ println! (" {}: {}" , linenumber , line );
70
+ }
71
+ ```
72
+ Outputs:
73
+ ```
74
+ 0: Content of line one
75
+ 1: Content of line two
76
+ 2: Content of line tree
77
+ 3: Content of line four
78
+ ```
You can’t perform that action at this time.
0 commit comments