auto merge of #17469 : sfackler/rust/into-result, r=aturon
This is the inverse of `Result::ok` and helps to bridge `Option` and `Result` based APIs.
This commit is contained in:
commit
606bf110bc
@ -145,10 +145,11 @@
|
|||||||
|
|
||||||
use cmp::{PartialEq, Eq, Ord};
|
use cmp::{PartialEq, Eq, Ord};
|
||||||
use default::Default;
|
use default::Default;
|
||||||
use slice::Slice;
|
|
||||||
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
|
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
|
||||||
use mem;
|
use mem;
|
||||||
|
use result::{Result, Ok, Err};
|
||||||
use slice;
|
use slice;
|
||||||
|
use slice::Slice;
|
||||||
|
|
||||||
// Note that this is not a lang item per se, but it has a hidden dependency on
|
// 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
|
// `Iterator`, which is one. The compiler assumes that the `next` method of
|
||||||
@ -439,6 +440,48 @@ impl<T> Option<T> {
|
|||||||
match self { None => def(), Some(t) => f(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.
|
/// Deprecated.
|
||||||
///
|
///
|
||||||
/// Applies a function to the contained value or does nothing.
|
/// Applies a function to the contained value or does nothing.
|
||||||
|
Loading…
Reference in New Issue
Block a user