Skip to content

Commit

Permalink
Merge pull request #1562 from Rqnsom/fibonacci_fix
Browse files Browse the repository at this point in the history
fix: Fibonacci sequence starts from zero
  • Loading branch information
marioidival authored Jun 28, 2022
2 parents f84c02e + 52bae54 commit 37ba461
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/trait/iter.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# Iterators

The [`Iterator`][iter] trait is used to implement iterators over collections such as arrays.
The [`Iterator`][iter] trait is used to implement iterators over collections
such as arrays.

The trait requires only a method to be defined for the `next` element,
which may be manually defined in an `impl` block or automatically
The trait requires only a method to be defined for the `next` element,
which may be manually defined in an `impl` block or automatically
defined (as in arrays and ranges).

As a point of convenience for common situations, the `for` construct
As a point of convenience for common situations, the `for` construct
turns some collections into iterators using the [`.into_iter()`][intoiter] method.

```rust,editable
Expand All @@ -20,22 +21,22 @@ struct Fibonacci {
impl Iterator for Fibonacci {
// We can refer to this type using Self::Item
type Item = u32;
// Here, we define the sequence using `.curr` and `.next`.
// The return type is `Option<T>`:
// * When the `Iterator` is finished, `None` is returned.
// * Otherwise, the next value is wrapped in `Some` and returned.
// We use Self::Item in the return type, so we can change
// the type without having to update the function signatures.
fn next(&mut self) -> Option<Self::Item> {
let new_next = self.curr + self.next;
let current = self.curr;
self.curr = self.next;
self.next = new_next;
self.next = current + self.next;
// Since there's no endpoint to a Fibonacci sequence, the `Iterator`
// will never return `None`, and `Some` is always returned.
Some(self.curr)
Some(current)
}
}
Expand Down

0 comments on commit 37ba461

Please sign in to comment.