I have seen inspect() used in a couple of pieces of source code from other people, but I can't figure out how to use it. There is only its online documentation which doesn't describe much:
fn inspect<F>(self, f: F) -> Inspect<Self, F> where F: FnMut(&Self::Item),Does something with each element of an iterator, passing the value on.
When using iterators, you’ll often chain several of them together. While working on such code, you might want to check out what’s happening at various parts in the pipeline. To do that, insert a call to
inspect().It’s more common for
inspect()to be used as a debugging tool than to exist in your final code, but applications may find it useful in certain situations when errors need to be logged before being discarded.
Does it print out a value passed into it to better understand the iterator?
No, it does not print anything, but gives you the chance to do so. An example usage of inspect could be:
let _: Vec<_> = (0..6)
.map(|x| x * 2)
.inspect(|x| println!("{}", x))
.collect();
In this example inspect is only used to debug the value of x.
And the intention behind inspect isn't much larger (you can't modify anything in the iterator).
This is very helpful when dealing with many chained iterators (eg. .map(...).filter(...).map(...).count()).
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