Skip to content

Commit da61494

Browse files
authored
Rollup merge of #141659 - tkr-sh:map-or-default, r=Amanieu
Add `Result::map_or_default` and `Option::map_or_default` Closes: #138068 _This PR has been recreated because of the inactivity of the author (Cf. #138068 (comment)
2 parents f953c6d + eed0659 commit da61494

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

library/core/src/option.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1253,6 +1253,36 @@ impl<T> Option<T> {
12531253
}
12541254
}
12551255

1256+
/// Maps an `Option<T>` to a `U` by applying function `f` to the contained
1257+
/// value if the option is [`Some`], otherwise if [`None`], returns the
1258+
/// [default value] for the type `U`.
1259+
///
1260+
/// # Examples
1261+
///
1262+
/// ```
1263+
/// #![feature(result_option_map_or_default)]
1264+
///
1265+
/// let x: Option<&str> = Some("hi");
1266+
/// let y: Option<&str> = None;
1267+
///
1268+
/// assert_eq!(x.map_or_default(|x| x.len()), 2);
1269+
/// assert_eq!(y.map_or_default(|y| y.len()), 0);
1270+
/// ```
1271+
///
1272+
/// [default value]: Default::default
1273+
#[inline]
1274+
#[unstable(feature = "result_option_map_or_default", issue = "138099")]
1275+
pub fn map_or_default<U, F>(self, f: F) -> U
1276+
where
1277+
U: Default,
1278+
F: FnOnce(T) -> U,
1279+
{
1280+
match self {
1281+
Some(t) => f(t),
1282+
None => U::default(),
1283+
}
1284+
}
1285+
12561286
/// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
12571287
/// [`Ok(v)`] and [`None`] to [`Err(err)`].
12581288
///

library/core/src/result.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -858,6 +858,36 @@ impl<T, E> Result<T, E> {
858858
}
859859
}
860860

861+
/// Maps a `Result<T, E>` to a `U` by applying function `f` to the contained
862+
/// value if the result is [`Ok`], otherwise if [`Err`], returns the
863+
/// [default value] for the type `U`.
864+
///
865+
/// # Examples
866+
///
867+
/// ```
868+
/// #![feature(result_option_map_or_default)]
869+
///
870+
/// let x: Result<_, &str> = Ok("foo");
871+
/// let y: Result<&str, _> = Err("bar");
872+
///
873+
/// assert_eq!(x.map_or_default(|x| x.len()), 3);
874+
/// assert_eq!(y.map_or_default(|y| y.len()), 0);
875+
/// ```
876+
///
877+
/// [default value]: Default::default
878+
#[inline]
879+
#[unstable(feature = "result_option_map_or_default", issue = "138099")]
880+
pub fn map_or_default<U, F>(self, f: F) -> U
881+
where
882+
U: Default,
883+
F: FnOnce(T) -> U,
884+
{
885+
match self {
886+
Ok(t) => f(t),
887+
Err(_) => U::default(),
888+
}
889+
}
890+
861891
/// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
862892
/// contained [`Err`] value, leaving an [`Ok`] value untouched.
863893
///

0 commit comments

Comments
 (0)