Skip to content

Commit dbef313

Browse files
committed
Add Result::unwrap_infallible
Implementation of rust-lang/rfcs#2799
1 parent f39205b commit dbef313

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/libcore/result.rs

+31
Original file line numberDiff line numberDiff line change
@@ -1060,6 +1060,37 @@ impl<T: Default, E> Result<T, E> {
10601060
}
10611061
}
10621062

1063+
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1064+
impl<T, E: Into<!>> Result<T, E> {
1065+
/// Unwraps a result that can never be an [`Err`], yielding the content of the [`Ok`].
1066+
///
1067+
/// Unlike [`unwrap`], this method is known to never panic on the
1068+
/// result types it is implemented for. Therefore, it can be used
1069+
/// instead of `unwrap` as a maintainability safeguard that will fail
1070+
/// to compile if the error type of the `Result` is later changed
1071+
/// to an error that can actually occur.
1072+
///
1073+
/// [`Ok`]: enum.Result.html#variant.Ok
1074+
/// [`Err`]: enum.Result.html#variant.Err
1075+
/// [`unwrap`]: enum.Result.html#method.unwrap
1076+
///
1077+
/// # Examples
1078+
///
1079+
/// Basic usage:
1080+
///
1081+
/// ```
1082+
/// let x = u64::try_from(42u32).unwrap_infallible();
1083+
/// assert_eq!(x, 42u64);
1084+
/// ```
1085+
#[inline]
1086+
pub fn unwrap_infallible(self) -> T {
1087+
match self {
1088+
Ok(x) => x,
1089+
Err(e) => e.into(),
1090+
}
1091+
}
1092+
}
1093+
10631094
#[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
10641095
impl<T: Deref, E> Result<T, E> {
10651096
/// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E>`.

0 commit comments

Comments
 (0)