Is there a method like `inspect_mut` on Iterator?

Ill just show the code I am working with:

vec.iter_mut()
    .filter(<by something>)
    .map(|x| {
        *x = 0;
        x
    }).count();

The map call there looks ugly to me.
I can't use inspect because then I get a &&mut and can't assign through it.
It seems i need something like inspect but giving me a mutable reference to the elements.

Or perhaps

I tried to collapse the map and count into:

.fold(0, |acc, x| {
    *x = 0;
    acc + 1
});

But funnily enough this was actually slightly slower

Another solution would be if there was some easy way to convert a FnX(&mut T) into a FnX(T) -> T

Actually that function is just

fn lift<T>(f: impl Fn(&mut T)) -> impl Fn(T) -> T {
    move |mut x| {
        f(&mut x);
        x
    }
}

But thats a bit hard to understand, a bit verbose, and would be cleaner using inspect_mut

I've looked through the docs and inspect_mut doesn't exist, so I guess my question is more is there a reason it couldn't exist?

1 Like

Ah, I just found this in Itertools:

The update method is what I want

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.