Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve docs for collecting into Options #56342

Merged
merged 1 commit into from
Dec 24, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 31 additions & 9 deletions src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if this is an obvious function or should be explain more (or use the explicit impl of checked adding as it did previously)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems fine as it is, maybe it comes best together if we mention that checked_add/_sub returns None on overflow, on this example or the next?

/// .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> {
Expand Down