rust-itertools / itertools

Extra iterator adaptors, iterator methods, free functions, and macros.
https://docs.rs/itertools/
Apache License 2.0
2.72k stars 309 forks source link

[Feature request] .apply() #811

Closed dev-ardi closed 10 months ago

dev-ardi commented 10 months ago
    fn apply<B, F>(self, f: F) -> Self
    where
        Self: Sized,
        F: FnMut(Self::Item),
    {
       f(self.item); // However this is done
        self
    }

Similar to foreach but doesn't consume the iterator. Equivalent to .map(|x| {[something with side effects]; x}) Useful for printing each element in the iterator for debugging, for example.

Philippe-Cholet commented 10 months ago

About the dbg PR alternative, I think about the inspect method: iter.inspect(|x| dbg!(x)).

If it's a method for our Itertools trait then what is .item?

If it's on each item like .map(|x| {[something with side effects]; x}), I think of our update adaptor: iter.update(|item/*: &mut Self::Item*/| ...).

Here, f takes ownership of the items. Should we clone them to return them anyway? Otherwise, there is for_each.

scottmcm commented 10 months ago

The signature as written can't work, since you're moving them item into the FnMut, which means it has to be map since there's no way to return the item afterwards.

I agree that this sounds like it's just inspect, where getting & not &mut is a feature.

dev-ardi commented 10 months ago

I agree