Iterator trait
- Rust course
- Intermediate
- Lesson 48/115
- 4 min
Build your own iterator by implementing the Iterator trait.
The Iterator trait
All iterators in Rust implement a single trait. The only required method is next; dozens of other methods (map, filter, sum...) come by default:
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
// map, filter, sum, collect ... default methods
}type Item is an associated type: it says what the iterator produces. next returns the next element inside Some, and None when finished.
Your own iterator
Implementing Iterator for a struct gives you all iterator methods for free:
struct Geri {
n: u32,
}
impl Iterator for Geri {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.n == 0 {
return None;
}
self.n -= 1;
Some(self.n + 1)
}
}
let v: Vec<u32> = Geri { n: 3 }.collect(); // [3, 2, 1]Practice Countdown
Write the Geri iterator above. Collect the elements of Geri { n: 3 } into a Vec<u32> and print it with {:?}.
Starter code
fn main() {
// buraya yaz
}Sample solution
struct Geri {
n: u32,
}
impl Iterator for Geri {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.n == 0 {
return None;
}
self.n -= 1;
Some(self.n + 1)
}
}
fn main() {
let v: Vec<u32> = Geri { n: 3 }.collect();
println!("{:?}", v);
}Expected output
[3, 2, 1]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why does <code>next</code> take <code>&mut self</code>?
- To delete elements
- It's a convention; not needed
- For thread safety
- The iterator advances its internal position on each call Correct answer
Explanation: An iterator keeps state (where it is); next changes that state.
2 Item type
impl Iterator for Geri {
type ____ = u32;
fn next(&mut self) -> Option<u32> { .. }
}
impl Iterator for Geri {
type Item = u32;
fn next(&mut self) -> Option<u32> { .. }
}
Explanation: Iterator's associated type is Item.
3 Piece and meaning
| Term | Meaning |
|---|---|
type Item |
Produced type |
fn next |
Required method |
Some(x) |
Next element |
None |
Finished |