Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fibonacci sequence starts from zero #1562

Merged
merged 1 commit into from
Jun 28, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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