Skip to content

Commit d5a61c0

Browse files
committed
Expand impl FromIterator for Result doc to include examples of Err and early termination.
1 parent 48af718 commit d5a61c0

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/libcore/result.rs

+28
Original file line numberDiff line numberDiff line change
@@ -1202,6 +1202,34 @@ impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
12021202
/// ).collect();
12031203
/// assert_eq!(res, Ok(vec![2, 3]));
12041204
/// ```
1205+
///
1206+
/// Here is another example that tries to subtract one from another list
1207+
/// of integers, this time checking for underflow:
1208+
///
1209+
/// ```
1210+
/// let v = vec![1, 2, 0];
1211+
/// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1212+
/// x.checked_sub(1).ok_or("Underflow!")
1213+
/// ).collect();
1214+
/// assert_eq!(res, Err("Underflow!"));
1215+
/// ```
1216+
///
1217+
/// Here is a variation on the previous example, showing that no
1218+
/// further elements are taken from `iter` after the first `Err`.
1219+
///
1220+
/// ```
1221+
/// let v = vec![3, 2, 1, 10];
1222+
/// let mut shared = 0;
1223+
/// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1224+
/// shared += x;
1225+
/// x.checked_sub(2).ok_or("Underflow!")
1226+
/// ).collect();
1227+
/// assert_eq!(res, Err("Underflow!"));
1228+
/// assert_eq!(shared, 6);
1229+
/// ```
1230+
///
1231+
/// Since the third element caused an underflow, no further elements were taken,
1232+
/// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
12051233
#[inline]
12061234
fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
12071235
// FIXME(#11084): This could be replaced with Iterator::scan when this

0 commit comments

Comments
 (0)