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

add Option::{err_or,err_or_else} methods under option_err_or gate #73040

Closed
wants to merge 1 commit into from
Closed
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
61 changes: 61 additions & 0 deletions src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,67 @@ impl<T> Option<T> {
}
}

/// Transforms the `Option<T>` into a [`Result<O, T>`], mapping [`Some(v)`] to
/// [`Err(v)`] and [`None`] to [`Ok(ok)`].
///
/// Arguments passed to `err_or` are eagerly evaluated; if you are passing the
/// result of a function call, it is recommended to use [`err_or_else`], which is
/// lazily evaluated.
///
/// [`Result<O, T>`]: ../../std/result/enum.Result.html
/// [`Err(v)`]: ../../std/result/enum.Result.html#variant.Err
/// [`Ok(ok)`]: ../../std/result/enum.Result.html#variant.Ok
/// [`None`]: #variant.None
/// [`Some(v)`]: #variant.Some
/// [`err_or_else`]: #method.err_or_else
///
/// # Examples
///
/// ```
/// #![feature(option_err_or)]
/// let x = Some("foo");
/// assert_eq!(x.err_or(0), Err("foo"));
///
/// let x: Option<&str> = None;
/// assert_eq!(x.err_or(0), Ok(0));
/// ```
#[inline]
#[unstable(feature = "option_err_or", issue = "none")]
pub fn err_or<O>(self, ok: O) -> Result<O, T> {
match self {
Some(v) => Err(v),
None => Ok(ok),
}
}

/// Transforms the `Option<T>` into a [`Result<O, T>`], mapping [`Some(v)`] to
/// [`Err(v)`] and [`None`] to [`Ok(ok())`].
///
/// [`Result<O, T>`]: ../../std/result/enum.Result.html
/// [`Err(v)`]: ../../std/result/enum.Result.html#variant.Err
/// [`Ok(ok())`]: ../../std/result/enum.Result.html#variant.Ok
/// [`None`]: #variant.None
/// [`Some(v)`]: #variant.Some
///
/// # Examples
///
/// ```
/// #![feature(option_err_or)]
/// let x = Some("foo");
/// assert_eq!(x.err_or_else(|| 0), Err("foo"));
///
/// let x: Option<&str> = None;
/// assert_eq!(x.err_or_else(|| 0), Ok(0));
/// ```
#[inline]
#[unstable(feature = "option_err_or", issue = "none")]
pub fn err_or_else<O, F: FnOnce() -> O>(self, ok: F) -> Result<O, T> {
match self {
Some(v) => Err(v),
None => Ok(ok()),
}
}

/////////////////////////////////////////////////////////////////////////
// Iterator constructors
/////////////////////////////////////////////////////////////////////////
Expand Down