diff options
| author | Mazdak Farrokhzad <twingoow@gmail.com> | 2018-12-23 23:09:00 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2018-12-23 23:09:00 +0100 |
| commit | 90a35861dd3f5bdf2b023c24c6dc45bb88485996 (patch) | |
| tree | 8b83b7aea92c446d0d34eef2870a23c1cc76fa09 | |
| parent | 4c971620e4bfa32df3e9da02772a2a1c68be004f (diff) | |
| parent | 2c0f011ca28dbe2941369315bd78a1dbbb7f950e (diff) | |
| download | rust-90a35861dd3f5bdf2b023c24c6dc45bb88485996.tar.gz rust-90a35861dd3f5bdf2b023c24c6dc45bb88485996.zip | |
Rollup merge of #56342 - killercup:collect-into-option-docs, r=bluss
Improve docs for collecting into `Option`s 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`.
| -rw-r--r-- | src/libcore/option.rs | 40 |
1 files changed, 31 insertions, 9 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 44d632ece05..dbad29229eb 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -1253,20 +1253,42 @@ impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> { /// returned. Should no [`None`][Option::None] occur, a container with the /// values of each [`Option`] is returned. /// - /// Here is an example which increments every integer in a vector, - /// checking for overflow: + /// # Examples + /// + /// Here is an example which increments every integer in a vector. + /// `We use the checked variant of `add` that returns `None` when the + /// calculation would result in an overflow. /// /// ``` - /// use std::u16; + /// let items = vec![0_u16, 1, 2]; + /// + /// let res: Option<Vec<u16>> = items + /// .iter() + /// .map(|x| x.checked_add(1)) + /// .collect(); /// - /// let v = vec![1, 2]; - /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16| - /// if x == u16::MAX { None } - /// else { Some(x + 1) } - /// ).collect(); - /// assert!(res == Some(vec![2, 3])); + /// assert_eq!(res, Some(vec![1, 2, 3])); /// ``` /// + /// As you can see, this will return the expected, valid items. + /// + /// Here is another example that tries to subtract one from another list + /// of integers, this time checking for underflow: + /// + /// ``` + /// let items = vec![2_u16, 1, 0]; + /// + /// let res: Option<Vec<u16>> = items + /// .iter() + /// .map(|x| x.checked_sub(1)) + /// .collect(); + /// + /// assert_eq!(res, None); + /// ``` + /// + /// Since the last element is zero, it would underflow. Thus, the resulting + /// value is `None`. + /// /// [`Iterator`]: ../iter/trait.Iterator.html #[inline] fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> { |
