Skip to content

Commit

Permalink
Rollup merge of rust-lang#66292 - lzutao:result-map_or, r=SimonSapin
Browse files Browse the repository at this point in the history
add Result::map_or

This PR adds this API to make it consistent with `Option::map_or`.

```rust
impl<T, E> Result<T, E> {
    pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
        match self {
            Ok(t) => f(t),
            Err(_) => default,
        }
    }
}
```

This API is very small. We already has a similar API for `Option::map_or`.
  • Loading branch information
JohnTitor committed Nov 13, 2019
2 parents 689cc04 + e8f3a9f commit 961d51d
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/libcore/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,28 @@ impl<T, E> Result<T, E> {
}
}

/// Applies a function to the contained value (if any),
/// or returns the provided default (if not).
///
/// # Examples
///
/// ```
/// #![feature(result_map_or)]
/// let x: Result<_, &str> = Ok("foo");
/// assert_eq!(x.map_or(42, |v| v.len()), 3);
///
/// let x: Result<&str, _> = Err("bar");
/// assert_eq!(x.map_or(42, |v| v.len()), 42);
/// ```
#[inline]
#[unstable(feature = "result_map_or", issue = "66293")]
pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
match self {
Ok(t) => f(t),
Err(_) => default,
}
}

/// Maps a `Result<T, E>` to `U` by applying a function to a
/// contained [`Ok`] value, or a fallback function to a
/// contained [`Err`] value.
Expand Down

0 comments on commit 961d51d

Please sign in to comment.