Is there an iterator consuming null overhead?

I often find that I am writing code like:

myvec.iter().map(|x| some_operation(x)).count()

The call countstarts a chain of iterators that will be consumed, but also produces, if not a single result, which is undesirable.

I'm looking for something like

myvec.iter().map(|x| some_operation(x)).consume()

which should be equivalent

for _ in myvec.iter().map(|x| some_operation(x)) {}
+4
source share
2 answers

No, Rust doesn't have that.

There have been several discussions, and even an RFC, about the existence of an operation for_each()on iterators that will close for each element of the iterator, consuming it, but nothing exists yet.

Use instead for:

for x in myvec.iter() {
    some_operation(x);
}

In this particular case, it looks better than iterator operations.

+7

Iterator::for_each , :

struct Int(i32);

impl Int {
    fn print(&self) {
        println!("{}", self.0)
    }
}

fn main() {
    [Int(1), Int(2), Int(3)].into_iter().for_each(Int::print);
}
+2

All Articles