Skip to content

Commit 2c0f011

Browse files
committed
Improve docs for collecting into Options
Changes the original example to use more idiomatic formatting as well as `.checked_add`. Also adds a second example to show a case where the `.collect` returns `None`.
1 parent ddab10a commit 2c0f011

File tree

1 file changed

+31
-9
lines changed

1 file changed

+31
-9
lines changed

src/libcore/option.rs

+31-9
Original file line numberDiff line numberDiff line change
@@ -1253,20 +1253,42 @@ impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
12531253
/// returned. Should no [`None`][Option::None] occur, a container with the
12541254
/// values of each [`Option`] is returned.
12551255
///
1256-
/// Here is an example which increments every integer in a vector,
1257-
/// checking for overflow:
1256+
/// # Examples
1257+
///
1258+
/// Here is an example which increments every integer in a vector.
1259+
/// `We use the checked variant of `add` that returns `None` when the
1260+
/// calculation would result in an overflow.
12581261
///
12591262
/// ```
1260-
/// use std::u16;
1263+
/// let items = vec![0_u16, 1, 2];
1264+
///
1265+
/// let res: Option<Vec<u16>> = items
1266+
/// .iter()
1267+
/// .map(|x| x.checked_add(1))
1268+
/// .collect();
12611269
///
1262-
/// let v = vec![1, 2];
1263-
/// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
1264-
/// if x == u16::MAX { None }
1265-
/// else { Some(x + 1) }
1266-
/// ).collect();
1267-
/// assert!(res == Some(vec![2, 3]));
1270+
/// assert_eq!(res, Some(vec![1, 2, 3]));
12681271
/// ```
12691272
///
1273+
/// As you can see, this will return the expected, valid items.
1274+
///
1275+
/// Here is another example that tries to subtract one from another list
1276+
/// of integers, this time checking for underflow:
1277+
///
1278+
/// ```
1279+
/// let items = vec![2_u16, 1, 0];
1280+
///
1281+
/// let res: Option<Vec<u16>> = items
1282+
/// .iter()
1283+
/// .map(|x| x.checked_sub(1))
1284+
/// .collect();
1285+
///
1286+
/// assert_eq!(res, None);
1287+
/// ```
1288+
///
1289+
/// Since the last element is zero, it would underflow. Thus, the resulting
1290+
/// value is `None`.
1291+
///
12701292
/// [`Iterator`]: ../iter/trait.Iterator.html
12711293
#[inline]
12721294
fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {

0 commit comments

Comments
 (0)