11# Iterators
22
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.
45
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
78defined (as in arrays and ranges).
89
9- As a point of convenience for common situations, the ` for ` construct
10+ As a point of convenience for common situations, the ` for ` construct
1011turns some collections into iterators using the [ ` .into_iter() ` ] [ intoiter ] method.
1112
1213``` rust,editable
@@ -20,22 +21,22 @@ struct Fibonacci {
2021impl Iterator for Fibonacci {
2122 // We can refer to this type using Self::Item
2223 type Item = u32;
23-
24+
2425 // Here, we define the sequence using `.curr` and `.next`.
2526 // The return type is `Option<T>`:
2627 // * When the `Iterator` is finished, `None` is returned.
2728 // * Otherwise, the next value is wrapped in `Some` and returned.
2829 // We use Self::Item in the return type, so we can change
2930 // the type without having to update the function signatures.
3031 fn next(&mut self) -> Option<Self::Item> {
31- let new_next = self.curr + self.next ;
32+ let current = self.curr;
3233
3334 self.curr = self.next;
34- self.next = new_next ;
35+ self.next = current + self.next ;
3536
3637 // Since there's no endpoint to a Fibonacci sequence, the `Iterator`
3738 // will never return `None`, and `Some` is always returned.
38- Some(self.curr )
39+ Some(current )
3940 }
4041}
4142
0 commit comments