Skip to content

Commit 18cf47b

Browse files
committed
Document additional use case for iter::inspect
1 parent 2612bbc commit 18cf47b

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/libcore/iter/iterator.rs

+29-2
Original file line numberDiff line numberDiff line change
@@ -1169,8 +1169,9 @@ pub trait Iterator {
11691169
/// happening at various parts in the pipeline. To do that, insert
11701170
/// a call to `inspect()`.
11711171
///
1172-
/// It's much more common for `inspect()` to be used as a debugging tool
1173-
/// than to exist in your final code, but never say never.
1172+
/// It's more common for `inspect()` to be used as a debugging tool than to
1173+
/// exist in your final code, but applications may find it useful in certain
1174+
/// situations when errors need to be logged before being discarded.
11741175
///
11751176
/// # Examples
11761177
///
@@ -1210,6 +1211,32 @@ pub trait Iterator {
12101211
/// about to filter: 3
12111212
/// 6
12121213
/// ```
1214+
///
1215+
/// Logging errors before discarding them:
1216+
///
1217+
/// ```
1218+
/// let lines = ["1", "2", "a"];
1219+
///
1220+
/// let sum: i32 = lines
1221+
/// .iter()
1222+
/// .map(|line| line.parse::<i32>())
1223+
/// .inspect(|num| {
1224+
/// if let Err(ref e) = *num {
1225+
/// println!("Parsing error: {}", e);
1226+
/// }
1227+
/// })
1228+
/// .filter_map(Result::ok)
1229+
/// .sum();
1230+
///
1231+
/// println!("Sum: {}", sum);
1232+
/// ```
1233+
///
1234+
/// This will print:
1235+
///
1236+
/// ```text
1237+
/// Parsing error: invalid digit found in string
1238+
/// Sum: 3
1239+
/// ```
12131240
#[inline]
12141241
#[stable(feature = "rust1", since = "1.0.0")]
12151242
fn inspect<F>(self, f: F) -> Inspect<Self, F> where

0 commit comments

Comments
 (0)