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)