From 593f9293b9a9e3c7ddd2a230578a2284a9163ec4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Tue, 23 Mar 2021 21:24:26 +0100 Subject: [PATCH 1/2] Add Result::into_err where the Ok variant can never happen --- library/core/src/result.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 2ce8a703c123e..20f8095b7d1ce 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1167,6 +1167,42 @@ impl> Result { } } +#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] +impl, E> Result { + /// Returns the contained [`Err`] value, but never panics. + /// + /// Unlike [`unwrap_err`], this method is known to never panic on the + /// result types it is implemented for. Therefore, it can be used + /// instead of `unwrap_err` as a maintainability safeguard that will fail + /// to compile if the ok type of the `Result` is later changed + /// to a type that can actually occur. + /// + /// [`unwrap_err`]: Result::unwrap_err + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// # #![feature(never_type)] + /// # #![feature(unwrap_infallible)] + /// + /// fn only_bad_news() -> Result { + /// Err("Oops, it failed".into()) + /// } + /// + /// let error: String = only_bad_news().into_err(); + /// println!("{}", error); + /// ``` + #[inline] + pub fn into_err(self) -> E { + match self { + Ok(x) => x.into(), + Err(e) => e, + } + } +} + impl Result { /// Converts from `Result` (or `&Result`) to `Result<&::Target, &E>`. /// From 3bf076e76b2afde77f1c0d2c763cef32407f0465 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Tue, 23 Mar 2021 21:27:38 +0100 Subject: [PATCH 2/2] Add test for Result::into_err --- library/core/tests/result.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/library/core/tests/result.rs b/library/core/tests/result.rs index 5fcd7b4d3a327..c461ab380ad3d 100644 --- a/library/core/tests/result.rs +++ b/library/core/tests/result.rs @@ -225,6 +225,28 @@ pub fn test_into_ok() { assert_eq!(infallible_op2().into_ok(), 667); } +#[test] +pub fn test_into_err() { + fn until_error_op() -> Result { + Err(666) + } + + assert_eq!(until_error_op().into_err(), 666); + + enum MyNeverToken {} + impl From for ! { + fn from(never: MyNeverToken) -> ! { + match never {} + } + } + + fn until_error_op2() -> Result { + Err(667) + } + + assert_eq!(until_error_op2().into_err(), 667); +} + #[test] fn test_try() { fn try_result_some() -> Option {