Iterators.
See module-level documentation for more details.
Implementing an iterator
Types that have Iterator semantics should implement next at a minimum. When the iterator can cheaply determine the number of remaining elements, it should also implement size_hint. This enables the collections constructed from iterators to efficiently reserve space for the elements and avoid reallocations. If size_hint returns a value, it should be exact.
All types implementing Iterator should also mix in IteratorExt, which provides a number of useful extension methods.
See also DoubleEndedIterator for iterators that can be iterated in reverse order.
Example
struct Countdown { counter: i32 }
impl Countdown {
use std::cmp::max;
use std::iter::{Iterator, IteratorExt};
fn next(self: &mut Countdown) -> Option<i32> {
if self.counter <= 0 {
Option::none()
} else {
let ret = Option::some(self.counter);
self.counter -= 1;
ret
}
}
fn size_hint(self: &Countdown) -> Option<usize> {
Option::some(max(0, self.counter) as usize)
}
mixin Iterator<Countdown, i32>;
mixin IteratorExt<Countdown, i32>;
}
// use `(1..=5).rev()` in real code
let countdown = Countdown { counter: 5 };
for i in countdown {
println!("{}", i);
}
println!("Ignition and Liftoff!");
Run this example
Required methods
-
Returns the next item, if any.
If the iterator has reached the end, it returns
Option::none()
.See Iterator for more information.