Rollup merge of #141659 - tkr-sh:map-or-default, r=Amanieu

Add `Result::map_or_default` and `Option::map_or_default`

Closes: https://github.com/rust-lang/rust/pull/138068

_This PR has been recreated because of the inactivity of the author (Cf. https://github.com/rust-lang/rust/pull/138068#issuecomment-2912412288)_
This commit is contained in:
Trevor Gross
2025-05-27 20:28:34 -04:00
committed by GitHub
2 changed files with 60 additions and 0 deletions
+30
View File
@@ -1253,6 +1253,36 @@ pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
}
}
/// Maps an `Option<T>` to a `U` by applying function `f` to the contained
/// value if the option is [`Some`], otherwise if [`None`], returns the
/// [default value] for the type `U`.
///
/// # Examples
///
/// ```
/// #![feature(result_option_map_or_default)]
///
/// let x: Option<&str> = Some("hi");
/// let y: Option<&str> = None;
///
/// assert_eq!(x.map_or_default(|x| x.len()), 2);
/// assert_eq!(y.map_or_default(|y| y.len()), 0);
/// ```
///
/// [default value]: Default::default
#[inline]
#[unstable(feature = "result_option_map_or_default", issue = "138099")]
pub fn map_or_default<U, F>(self, f: F) -> U
where
U: Default,
F: FnOnce(T) -> U,
{
match self {
Some(t) => f(t),
None => U::default(),
}
}
/// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
/// [`Ok(v)`] and [`None`] to [`Err(err)`].
///
+30
View File
@@ -858,6 +858,36 @@ pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f:
}
}
/// Maps a `Result<T, E>` to a `U` by applying function `f` to the contained
/// value if the result is [`Ok`], otherwise if [`Err`], returns the
/// [default value] for the type `U`.
///
/// # Examples
///
/// ```
/// #![feature(result_option_map_or_default)]
///
/// let x: Result<_, &str> = Ok("foo");
/// let y: Result<&str, _> = Err("bar");
///
/// assert_eq!(x.map_or_default(|x| x.len()), 3);
/// assert_eq!(y.map_or_default(|y| y.len()), 0);
/// ```
///
/// [default value]: Default::default
#[inline]
#[unstable(feature = "result_option_map_or_default", issue = "138099")]
pub fn map_or_default<U, F>(self, f: F) -> U
where
U: Default,
F: FnOnce(T) -> U,
{
match self {
Ok(t) => f(t),
Err(_) => U::default(),
}
}
/// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
/// contained [`Err`] value, leaving an [`Ok`] value untouched.
///