Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tap() an iterator?

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

like image 537
Jay Avatar asked Jun 08 '26 06:06

Jay


2 Answers

This is on Iterator as .inspect():

foo.into_iter()
  .filter(|x| x == target)
  .inspect(|x| println!("{:?}", x))
  .map(|c| c.result)
like image 102
kmdreko Avatar answered Jun 10 '26 20:06

kmdreko


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.

like image 22
Aleksander Krauze Avatar answered Jun 10 '26 19:06

Aleksander Krauze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!