The Iterator Trait
next and laziness.
What Is an Iterator?
An iterator is anything that produces a sequence of values, one at a time. In Rust, iterators are the idiomatic way to process collections like vectors, ranges, and slices.
The whole concept is built on a single trait: Iterator. Once a type implements it, you get dozens of useful methods for free.
The Iterator Trait
The Iterator trait has one required method, next, and one associated type, Item:
type Item— the kind of value producedfn next(&mut self) -> Option<Self::Item>— returns the next value
It returns Some(value) while values remain, then None when finished.
fn main() {
let v = vec![10, 20, 30];
let mut it = v.iter();
println!("{:?}", it.next());
println!("{:?}", it.next());
println!("{:?}", it.next());
println!("{:?}", it.next());
}All lessons in this course
- The Iterator Trait
- map, filter, collect
- Adapters and Consumers
- Custom Iterators