Skip to content

Commit 606bf11

Browse files
committed
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.
2 parents 43d7d7c + 0c8878d commit 606bf11

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

src/libcore/option.rs

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,10 +145,11 @@
145145

146146
use cmp::{PartialEq, Eq, Ord};
147147
use default::Default;
148-
use slice::Slice;
149148
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
150149
use mem;
150+
use result::{Result, Ok, Err};
151151
use slice;
152+
use slice::Slice;
152153

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

443+
/// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
444+
/// `Ok(v)` and `None` to `Err(err)`.
445+
///
446+
/// # Example
447+
///
448+
/// ```
449+
/// let x = Some("foo");
450+
/// assert_eq!(x.ok_or(0i), Ok("foo"));
451+
///
452+
/// let x: Option<&str> = None;
453+
/// assert_eq!(x.ok_or(0i), Err(0i));
454+
/// ```
455+
#[inline]
456+
#[experimental]
457+
pub fn ok_or<E>(self, err: E) -> Result<T, E> {
458+
match self {
459+
Some(v) => Ok(v),
460+
None => Err(err),
461+
}
462+
}
463+
464+
/// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
465+
/// `Ok(v)` and `None` to `Err(err())`.
466+
///
467+
/// # Example
468+
///
469+
/// ```
470+
/// let x = Some("foo");
471+
/// assert_eq!(x.ok_or_else(|| 0i), Ok("foo"));
472+
///
473+
/// let x: Option<&str> = None;
474+
/// assert_eq!(x.ok_or_else(|| 0i), Err(0i));
475+
/// ```
476+
#[inline]
477+
#[experimental]
478+
pub fn ok_or_else<E>(self, err: || -> E) -> Result<T, E> {
479+
match self {
480+
Some(v) => Ok(v),
481+
None => Err(err()),
482+
}
483+
}
484+
442485
/// Deprecated.
443486
///
444487
/// Applies a function to the contained value or does nothing.

0 commit comments

Comments
 (0)