From a20013b129c10907aee0bfb5bf1cac387e48eb51 Mon Sep 17 00:00:00 2001 From: Mikhail Zabaluev Date: Sat, 2 Nov 2019 20:13:32 +0200 Subject: [PATCH] Add Result::unwrap_infallible Implementation of https://github.com/rust-lang/rfcs/pull/2799 --- src/libcore/result.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/libcore/result.rs b/src/libcore/result.rs index fb4dc62d8c17..ed3b37ad2a57 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -1083,6 +1083,44 @@ impl Result { } } +#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] +impl> Result { + /// Unwraps a result that can never be an [`Err`], yielding the content of the [`Ok`]. + /// + /// Unlike [`unwrap`], this method is known to never panic on the + /// result types it is implemented for. Therefore, it can be used + /// instead of `unwrap` as a maintainability safeguard that will fail + /// to compile if the error type of the `Result` is later changed + /// to an error that can actually occur. + /// + /// [`Ok`]: enum.Result.html#variant.Ok + /// [`Err`]: enum.Result.html#variant.Err + /// [`unwrap`]: enum.Result.html#method.unwrap + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// # #![feature(never_type)] + /// # #![feature(unwrap_infallible)] + /// + /// fn only_good_news() -> Result { + /// Ok("this is fine".into()) + /// } + /// + /// let s: String = only_good_news().unwrap_infallible(); + /// println!("{}", s); + /// ``` + #[inline] + pub fn unwrap_infallible(self) -> T { + match self { + Ok(x) => x, + Err(e) => e.into(), + } + } +} + #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")] impl Result { /// Converts from `Result` (or `&Result`) to `Result<&T::Target, &E>`.