Skip to content

Commit 921a820

Browse files
authored
Rollup merge of #83421 - faern:add-into-err, r=joshtriplett
Add Result::into_err where the Ok variant is the never type Equivalent of #66045 but for the inverse situation where `T: Into<!>` rather than `E: Into<!>`. I'm using the same feature gate name. I can't see why one of these methods would be OK to stabilize but not the other. Tracking issue: #61695
2 parents 72a2d0e + 3bf076e commit 921a820

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-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
///

library/core/tests/result.rs

+22
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,28 @@ pub fn test_into_ok() {
225225
assert_eq!(infallible_op2().into_ok(), 667);
226226
}
227227

228+
#[test]
229+
pub fn test_into_err() {
230+
fn until_error_op() -> Result<!, isize> {
231+
Err(666)
232+
}
233+
234+
assert_eq!(until_error_op().into_err(), 666);
235+
236+
enum MyNeverToken {}
237+
impl From<MyNeverToken> for ! {
238+
fn from(never: MyNeverToken) -> ! {
239+
match never {}
240+
}
241+
}
242+
243+
fn until_error_op2() -> Result<MyNeverToken, isize> {
244+
Err(667)
245+
}
246+
247+
assert_eq!(until_error_op2().into_err(), 667);
248+
}
249+
228250
#[test]
229251
fn test_try() {
230252
fn try_result_some() -> Option<u8> {

0 commit comments

Comments
 (0)