]> git.lizzy.rs Git - rust.git/commitdiff
Add Option::{ok_or, ok_or_else}
authorSteven Fackler <sfackler@gmail.com>
Tue, 23 Sep 2014 06:18:30 +0000 (23:18 -0700)
committerSteven Fackler <sfackler@gmail.com>
Fri, 26 Sep 2014 16:11:53 +0000 (09:11 -0700)
These are the inverses of `Result::ok` and help to bridge `Option` and
`Result` based APIs.

src/libcore/option.rs

index c98a2d124854b77c5fd198acff8bac15b9640866..77fe55aadee480c67a317d6afc3dad9bea4c31f4 100644 (file)
 
 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 @@ pub fn map_or_else<U>(self, def: || -> U, f: |T| -> U) -> U {
         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.