Skip to content

Commit

Permalink
Add Result::into_err where the Ok variant can never happen
Browse files Browse the repository at this point in the history
  • Loading branch information
faern committed Mar 23, 2021
1 parent 79e5814 commit 593f929
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions library/core/src/result.rs
Expand Up @@ -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>`.
///
Expand Down

0 comments on commit 593f929

Please sign in to comment.