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)) {}
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With