Closed
Description
Currently, mapping methods for iterator, e.g. map
and filter
are implemented in a lazy manner. Which means they would not be calculated until further consumption
.
However, sometimes it can be the case that given an Iterator
(whatever it actually is) . we just wanted its side-effect and to simply consume
it. for instance :
#[derive(Debug)]
struct Item(i32);
fn take_iter<T : Iterator>(iter: T) {
// we just want to consume the `iter` here
// do something else
}
fn main() {
let ve = vec![Item(1), Item(2), Item(3), Item(1)];
take_iter(ve.iter().filter(|value| value.0 < 3).map(|value| {
println!("{:?}", value);
value
}));
}
Currently, there're several ways of achieving this goal, for example :
fn take_iter<T : Iterator>(iter: T) {
iter.for_each(|_| {}); // consumed
// do something else
}
fn take_iter<T : Iterator>(iter: T) {
iter.count(); // consumed
// do something else
}
While they're both usable, it's obvious that these methods are at the cost of efficiency, for_each
yields a call to closure which is totally unnecessary, while count
finally counting the number of elements in vain.