diff options
| author | Linus Färnstrand <faern@faern.net> | 2021-03-23 21:24:26 +0100 |
|---|---|---|
| committer | Linus Färnstrand <faern@faern.net> | 2021-03-23 21:24:26 +0100 |
| commit | 593f9293b9a9e3c7ddd2a230578a2284a9163ec4 (patch) | |
| tree | c1876ae12c56e93fb15f520b56ee50b30d8bb6d9 | |
| parent | 79e5814f4520f2c51b5307421db45cd82d134e76 (diff) | |
| download | rust-593f9293b9a9e3c7ddd2a230578a2284a9163ec4.tar.gz rust-593f9293b9a9e3c7ddd2a230578a2284a9163ec4.zip | |
Add Result::into_err where the Ok variant can never happen
| -rw-r--r-- | library/core/src/result.rs | 36 |
1 files changed, 36 insertions, 0 deletions
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 @@ impl<T, E: Into<!>> Result<T, E> { } } +#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] +impl<T: Into<!>, E> Result<T, E> { + /// 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<!, String> { + /// 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<T: Deref, E> Result<T, E> { /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`. /// |
