Skip to content

Commit 593f929

Browse files
committed
Add Result::into_err where the Ok variant can never happen
1 parent 79e5814 commit 593f929

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

library/core/src/result.rs

+36
Original file line numberDiff line numberDiff line change
@@ -1167,6 +1167,42 @@ impl<T, E: Into<!>> Result<T, E> {
11671167
}
11681168
}
11691169

1170+
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1171+
impl<T: Into<!>, E> Result<T, E> {
1172+
/// Returns the contained [`Err`] value, but never panics.
1173+
///
1174+
/// Unlike [`unwrap_err`], this method is known to never panic on the
1175+
/// result types it is implemented for. Therefore, it can be used
1176+
/// instead of `unwrap_err` as a maintainability safeguard that will fail
1177+
/// to compile if the ok type of the `Result` is later changed
1178+
/// to a type that can actually occur.
1179+
///
1180+
/// [`unwrap_err`]: Result::unwrap_err
1181+
///
1182+
/// # Examples
1183+
///
1184+
/// Basic usage:
1185+
///
1186+
/// ```
1187+
/// # #![feature(never_type)]
1188+
/// # #![feature(unwrap_infallible)]
1189+
///
1190+
/// fn only_bad_news() -> Result<!, String> {
1191+
/// Err("Oops, it failed".into())
1192+
/// }
1193+
///
1194+
/// let error: String = only_bad_news().into_err();
1195+
/// println!("{}", error);
1196+
/// ```
1197+
#[inline]
1198+
pub fn into_err(self) -> E {
1199+
match self {
1200+
Ok(x) => x.into(),
1201+
Err(e) => e,
1202+
}
1203+
}
1204+
}
1205+
11701206
impl<T: Deref, E> Result<T, E> {
11711207
/// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
11721208
///

0 commit comments

Comments
 (0)