X-Git-Url: https://git.lizzy.rs/?a=blobdiff_plain;f=library%2Fcore%2Fsrc%2Fresult.rs;h=20f8095b7d1cee998b7115c3949b65514839ed01;hb=ad2a80e412768fd2c9a162a3b68e1489af446f2f;hp=2ce8a703c123ef165e5268e1b9d47e284d8e97e9;hpb=a55b192d5942efcaad6901dcd21ffe28316ca20a;p=rust.git diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 2ce8a703c12..20f8095b7d1 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1167,6 +1167,42 @@ pub fn into_ok(self) -> T { } } +#[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>`. ///