diff --git a/src/libcore/result.rs b/src/libcore/result.rs index fb4dc62d8c176..ea2dd77f4efbb 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().into_ok(); + /// println!("{}", s); + /// ``` + #[inline] + pub fn into_ok(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>`. diff --git a/src/libcore/tests/lib.rs b/src/libcore/tests/lib.rs index 1f20ebc01e993..4656024241804 100644 --- a/src/libcore/tests/lib.rs +++ b/src/libcore/tests/lib.rs @@ -39,6 +39,8 @@ #![feature(slice_from_raw_parts)] #![feature(const_slice_from_raw_parts)] #![feature(const_raw_ptr_deref)] +#![feature(never_type)] +#![feature(unwrap_infallible)] extern crate test; diff --git a/src/libcore/tests/result.rs b/src/libcore/tests/result.rs index 163f8d0ab3797..cac15a6b32414 100644 --- a/src/libcore/tests/result.rs +++ b/src/libcore/tests/result.rs @@ -197,6 +197,28 @@ pub fn test_unwrap_or_default() { assert_eq!(op2().unwrap_or_default(), 0); } +#[test] +pub fn test_into_ok() { + fn infallible_op() -> Result { + Ok(666) + } + + assert_eq!(infallible_op().into_ok(), 666); + + enum MyNeverToken {} + impl From for ! { + fn from(never: MyNeverToken) -> ! { + match never {} + } + } + + fn infallible_op2() -> Result { + Ok(667) + } + + assert_eq!(infallible_op2().into_ok(), 667); +} + #[test] fn test_try() { fn try_result_some() -> Option {