Iterator::inspect() 是做什么的?

What does Iterator::inspect() do?

我看过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,描述不多:

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.

它是否打印出传递给它的值以更好地理解迭代器?

不,它不打印任何东西,但让您有机会这样做。 inspect 的示例用法可以是:

let _: Vec<_> = (0..6)
        .map(|x| x * 2)
        .inspect(|x| println!("{}", x))
        .collect();

本例中inspect仅用于调试x的值。 inspect 背后的意图并不大(您不能在迭代器中修改任何内容)。

这在处理许多链式迭代器(例如 .map(...).filter(...).map(...).count())时非常有用。