Skip to content

Document additional use case for iter::inspect #51142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 29, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions src/libcore/iter/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1169,8 +1169,9 @@ pub trait Iterator {
/// happening at various parts in the pipeline. To do that, insert
/// a call to `inspect()`.
///
/// It's much more common for `inspect()` to be used as a debugging tool
/// than to exist in your final code, but never say never.
/// 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.
///
/// # Examples
///
Expand Down Expand Up @@ -1210,6 +1211,32 @@ pub trait Iterator {
/// about to filter: 3
/// 6
/// ```
///
/// Logging errors before discarding them:
///
/// ```
/// let lines = ["1", "2", "a"];
///
/// let sum: i32 = lines
/// .iter()
/// .map(|line| line.parse::<i32>())
/// .inspect(|num| {
/// if let Err(ref e) = *num {
/// println!("Parsing error: {}", e);
/// }
/// })
/// .filter_map(Result::ok)
/// .sum();
///
/// println!("Sum: {}", sum);
/// ```
///
/// This will print:
///
/// ```text
/// Parsing error: invalid digit found in string
/// Sum: 3
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn inspect<F>(self, f: F) -> Inspect<Self, F> where
Expand Down