Skip to content

Commit 86599e0

Browse files
committed
Add Result::map_or_default and Option::map_or_default
1 parent 4559163 commit 86599e0

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

library/core/src/option.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,6 +1226,33 @@ impl<T> Option<T> {
12261226
}
12271227
}
12281228

1229+
/// Maps an `Option<T>` to a `U` by applying function `f` if the contained value
1230+
/// is [`Some`], otherwise if [`None`], returns the [default value] for the type `U`.
1231+
///
1232+
/// # Examples
1233+
///
1234+
/// ```
1235+
/// let x: Option<&str> = Some("hi");
1236+
/// let y: Option<&str> = None;
1237+
///
1238+
/// assert_eq!(x.map_or_default(|x| x.len()), 2);
1239+
/// assert_eq!(y.map_or_default(|y| y.len()), 0);
1240+
/// ```
1241+
///
1242+
/// [default value]: Default::default
1243+
#[inline]
1244+
#[unstable(feature = "result_option_map_or_default", issue = "none")]
1245+
pub fn map_or_default<U, F>(self, f: F) -> U
1246+
where
1247+
U: Default,
1248+
F: FnOnce(T) -> U,
1249+
{
1250+
match self {
1251+
Some(t) => f(t),
1252+
None => U::default(),
1253+
}
1254+
}
1255+
12291256
/// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
12301257
/// [`Ok(v)`] and [`None`] to [`Err(err)`].
12311258
///

library/core/src/result.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -830,6 +830,33 @@ impl<T, E> Result<T, E> {
830830
}
831831
}
832832

833+
/// Maps a `Result<T, E>` to a `U` by applying function `f` if the contained value
834+
/// is [`Ok`], otherwise if [`Err`], returns the [default value] for the type `U`.
835+
///
836+
/// # Examples
837+
///
838+
/// ```
839+
/// let x: Result<_, &str> = Ok("foo");
840+
/// let y: Result<&str, _> = Err("bar");
841+
///
842+
/// assert_eq!(x.map_or_default(|x| x.len()), 3);
843+
/// assert_eq!(y.map_or_default(|y| y.len()), 0);
844+
/// ```
845+
///
846+
/// [default value]: Default::default
847+
#[inline]
848+
#[unstable(feature = "result_option_map_or_default", issue = "none")]
849+
pub fn map_or_default<U, F>(self, f: F) -> U
850+
where
851+
U: Default,
852+
F: FnOnce(T) -> U,
853+
{
854+
match self {
855+
Ok(t) => f(t),
856+
Err(_) => U::default(),
857+
}
858+
}
859+
833860
/// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
834861
/// contained [`Err`] value, leaving an [`Ok`] value untouched.
835862
///

0 commit comments

Comments
 (0)