diff options
| author | Felix S. Klock II <pnkfelix@pnkfx.org> | 2019-03-20 13:09:22 +0100 |
|---|---|---|
| committer | Felix S. Klock II <pnkfelix@pnkfx.org> | 2019-03-22 12:44:08 +0100 |
| commit | d5a61c0be25d47c39ab7909b83b3a2765a282eb1 (patch) | |
| tree | 03c228f3e51595bcaaf03b73a151229bac449874 | |
| parent | 48af7189c2f0e69c16611c261c4ded84c0ac305d (diff) | |
| download | rust-d5a61c0be25d47c39ab7909b83b3a2765a282eb1.tar.gz rust-d5a61c0be25d47c39ab7909b83b3a2765a282eb1.zip | |
Expand `impl FromIterator for Result` doc to include examples of `Err` and early termination.
| -rw-r--r-- | src/libcore/result.rs | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 967f7e3e2fe..490cd5bb3fe 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -1202,6 +1202,34 @@ impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> { /// ).collect(); /// assert_eq!(res, Ok(vec![2, 3])); /// ``` + /// + /// Here is another example that tries to subtract one from another list + /// of integers, this time checking for underflow: + /// + /// ``` + /// let v = vec![1, 2, 0]; + /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| + /// x.checked_sub(1).ok_or("Underflow!") + /// ).collect(); + /// assert_eq!(res, Err("Underflow!")); + /// ``` + /// + /// Here is a variation on the previous example, showing that no + /// further elements are taken from `iter` after the first `Err`. + /// + /// ``` + /// let v = vec![3, 2, 1, 10]; + /// let mut shared = 0; + /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| + /// shared += x; + /// x.checked_sub(2).ok_or("Underflow!") + /// ).collect(); + /// assert_eq!(res, Err("Underflow!")); + /// assert_eq!(shared, 6); + /// ``` + /// + /// Since the third element caused an underflow, no further elements were taken, + /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16. #[inline] fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> { // FIXME(#11084): This could be replaced with Iterator::scan when this |
