Skip to content

Add Option::into_result #17469

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

Merged
merged 1 commit into from
Sep 27, 2014
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
45 changes: 44 additions & 1 deletion src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,11 @@

use cmp::{PartialEq, Eq, Ord};
use default::Default;
use slice::Slice;
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use mem;
use result::{Result, Ok, Err};
use slice;
use slice::Slice;

// Note that this is not a lang item per se, but it has a hidden dependency on
// `Iterator`, which is one. The compiler assumes that the `next` method of
Expand Down Expand Up @@ -439,6 +440,48 @@ impl<T> Option<T> {
match self { None => def(), Some(t) => f(t) }
}

/// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
/// `Ok(v)` and `None` to `Err(err)`.
///
/// # Example
///
/// ```
/// let x = Some("foo");
/// assert_eq!(x.ok_or(0i), Ok("foo"));
///
/// let x: Option<&str> = None;
/// assert_eq!(x.ok_or(0i), Err(0i));
/// ```
#[inline]
#[experimental]
pub fn ok_or<E>(self, err: E) -> Result<T, E> {
match self {
Some(v) => Ok(v),
None => Err(err),
}
}

/// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
/// `Ok(v)` and `None` to `Err(err())`.
///
/// # Example
///
/// ```
/// let x = Some("foo");
/// assert_eq!(x.ok_or_else(|| 0i), Ok("foo"));
///
/// let x: Option<&str> = None;
/// assert_eq!(x.ok_or_else(|| 0i), Err(0i));
/// ```
#[inline]
#[experimental]
pub fn ok_or_else<E>(self, err: || -> E) -> Result<T, E> {
match self {
Some(v) => Ok(v),
None => Err(err()),
}
}

/// Deprecated.
///
/// Applies a function to the contained value or does nothing.
Expand Down