2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
minutes: 5
|
|
|
|
---
|
|
|
|
|
2023-12-01 19:20:28 +01:00
|
|
|
# `Iterator`
|
2022-12-21 16:36:30 +01:00
|
|
|
|
2023-11-29 10:39:24 -05:00
|
|
|
The [`Iterator`][1] trait supports iterating over values in a collection. It
|
2023-12-31 00:15:07 +01:00
|
|
|
requires a `next` method and provides lots of methods. Many standard library
|
|
|
|
types implement `Iterator`, and you can implement it yourself, too:
|
2022-12-21 16:36:30 +01:00
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
struct Fibonacci {
|
|
|
|
curr: u32,
|
|
|
|
next: u32,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Iterator for Fibonacci {
|
|
|
|
type Item = u32;
|
|
|
|
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
|
|
let new_next = self.curr + self.next;
|
|
|
|
self.curr = self.next;
|
|
|
|
self.next = new_next;
|
|
|
|
Some(self.curr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let fib = Fibonacci { curr: 0, next: 1 };
|
|
|
|
for (i, n) in fib.enumerate().take(5) {
|
|
|
|
println!("fib({i}): {n}");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
2023-01-16 12:31:24 +00:00
|
|
|
|
|
|
|
<details>
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- The `Iterator` trait implements many common functional programming operations
|
|
|
|
over collections (e.g. `map`, `filter`, `reduce`, etc). This is the trait
|
|
|
|
where you can find all the documentation about them. In Rust these functions
|
|
|
|
should produce the code as efficient as equivalent imperative implementations.
|
2023-11-29 10:39:24 -05:00
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- `IntoIterator` is the trait that makes for loops work. It is implemented by
|
|
|
|
collection types such as `Vec<T>` and references to them such as `&Vec<T>` and
|
|
|
|
`&[T]`. Ranges also implement it. This is why you can iterate over a vector
|
|
|
|
with `for i in some_vec { .. }` but `some_vec.next()` doesn't exist.
|
2023-03-28 15:42:56 -04:00
|
|
|
|
2023-01-16 12:31:24 +00:00
|
|
|
</details>
|
2023-02-09 21:47:47 +00:00
|
|
|
|
|
|
|
[1]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
|