1
1
# Iterators
2
2
3
- The [ ` Iterator ` ] [ iter ] trait is used to implement iterators over collections such as arrays.
3
+ The [ ` Iterator ` ] [ iter ] trait is used to implement iterators over collections
4
+ such as arrays.
4
5
5
- The trait requires only a method to be defined for the ` next ` element,
6
- which may be manually defined in an ` impl ` block or automatically
6
+ The trait requires only a method to be defined for the ` next ` element,
7
+ which may be manually defined in an ` impl ` block or automatically
7
8
defined (as in arrays and ranges).
8
9
9
- As a point of convenience for common situations, the ` for ` construct
10
+ As a point of convenience for common situations, the ` for ` construct
10
11
turns some collections into iterators using the [ ` .into_iter() ` ] [ intoiter ] method.
11
12
12
13
``` rust,editable
@@ -20,22 +21,22 @@ struct Fibonacci {
20
21
impl Iterator for Fibonacci {
21
22
// We can refer to this type using Self::Item
22
23
type Item = u32;
23
-
24
+
24
25
// Here, we define the sequence using `.curr` and `.next`.
25
26
// The return type is `Option<T>`:
26
27
// * When the `Iterator` is finished, `None` is returned.
27
28
// * Otherwise, the next value is wrapped in `Some` and returned.
28
29
// We use Self::Item in the return type, so we can change
29
30
// the type without having to update the function signatures.
30
31
fn next(&mut self) -> Option<Self::Item> {
31
- let new_next = self.curr + self.next ;
32
+ let current = self.curr;
32
33
33
34
self.curr = self.next;
34
- self.next = new_next ;
35
+ self.next = current + self.next ;
35
36
36
37
// Since there's no endpoint to a Fibonacci sequence, the `Iterator`
37
38
// will never return `None`, and `Some` is always returned.
38
- Some(self.curr )
39
+ Some(current )
39
40
}
40
41
}
41
42
0 commit comments