Skip to content

Commit 48af718

Browse files
committed
Expand impl FromIterator for Option doc to include example of early termination.
1 parent 0c8700b commit 48af718

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/libcore/option.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1315,6 +1315,26 @@ impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
13151315
/// Since the last element is zero, it would underflow. Thus, the resulting
13161316
/// value is `None`.
13171317
///
1318+
/// Here is a variation on the previous example, showing that no
1319+
/// further elements are taken from `iter` after the first `None`.
1320+
///
1321+
/// ```
1322+
/// let items = vec![3_u16, 2, 1, 10];
1323+
///
1324+
/// let mut shared = 0;
1325+
///
1326+
/// let res: Option<Vec<u16>> = items
1327+
/// .iter()
1328+
/// .map(|x| shared += x; x.checked_sub(2))
1329+
/// .collect();
1330+
///
1331+
/// assert_eq!(res, None);
1332+
/// assert_eq!(shared, 6);
1333+
/// ```
1334+
///
1335+
/// Since the third element caused an underflow, no further elements were taken,
1336+
/// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1337+
///
13181338
/// [`Iterator`]: ../iter/trait.Iterator.html
13191339
#[inline]
13201340
fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {

0 commit comments

Comments
 (0)