diff options
| author | Steven Fackler <sfackler@gmail.com> | 2014-09-22 23:18:30 -0700 |
|---|---|---|
| committer | Steven Fackler <sfackler@gmail.com> | 2014-09-26 09:11:53 -0700 |
| commit | 0c8878d04258564b1866654a9866c5fbf2df6b68 (patch) | |
| tree | 5ca1c7a106bd224a6cd2a3dd26a0b7086b70e8d7 /src | |
| parent | 3f299ff19ddb3ee4752e6db120689189ab4c4231 (diff) | |
| download | rust-0c8878d04258564b1866654a9866c5fbf2df6b68.tar.gz rust-0c8878d04258564b1866654a9866c5fbf2df6b68.zip | |
Add Option::{ok_or, ok_or_else}
These are the inverses of `Result::ok` and help to bridge `Option` and `Result` based APIs.
Diffstat (limited to 'src')
| -rw-r--r-- | src/libcore/option.rs | 45 |
1 files changed, 44 insertions, 1 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs index c98a2d12485..77fe55aadee 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -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 @@ -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. |
