What's the Rust equivalent of tap()?
It calls a function on each item in the iterator like map() but instead of passing the value returned by the function, tap() returns the original item.
For example, I'd like to call println!() in the middle of my stream somehow:
foo.into_iter()
.filter(|x| x == target)
.tap(|x| println!("{:?}", x)) // <-- what goes here?
.map(|c| c.result)
Correction:
tap() calls the closure once on the entire iterator
inspect() calls the closure on each item in the iterator
This is on Iterator as .inspect():
foo.into_iter()
.filter(|x| x == target)
.inspect(|x| println!("{:?}", x))
.map(|c| c.result)
What you described is not tap, but inspect, as @kmdreko pointed out. A general purpose tap (alongside with a general purpose pipe - generic map which signature you could express as a -> (a -> b) -> b) is implemented by third-party tap library.
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