Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a zero-overhead consuming iterator?

Tags:

rust

I often find myself writing code like:

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

The invocation of count triggers the iterator chain to be consumed, but also produces as non-unit result which is undesired.

I am looking for something like

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

which should be equivalent to

for _ in myvec.iter().map(|x| some_operation(x)) {}
like image 846
Byron Avatar asked Jan 27 '15 07:01

Byron


2 Answers

Iterator::for_each does what you want:

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);
}
like image 149
Boiethios Avatar answered Sep 21 '22 22:09

Boiethios


No, Rust does not have this.

There were several discussions and even an RFC about having a for_each() operation on iterators which will execute a closure for each element of an iterator, consuming it, but nothing is there yet.

Consider using for loop instead:

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

In this particular case it does look better than iterator operations.

like image 43
Vladimir Matveev Avatar answered Sep 17 '22 22:09

Vladimir Matveev