Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Result::into_err where the Ok variant is the never type #83421

Merged
merged 2 commits into from
Mar 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions library/core/src/result.rs
Original file line number Diff line number Diff line change
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
22 changes: 22 additions & 0 deletions library/core/tests/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,28 @@ pub fn test_into_ok() {
assert_eq!(infallible_op2().into_ok(), 667);
}

#[test]
pub fn test_into_err() {
fn until_error_op() -> Result<!, isize> {
Err(666)
}

assert_eq!(until_error_op().into_err(), 666);

enum MyNeverToken {}
impl From<MyNeverToken> for ! {
fn from(never: MyNeverToken) -> ! {
match never {}
}
}

fn until_error_op2() -> Result<MyNeverToken, isize> {
Err(667)
}

assert_eq!(until_error_op2().into_err(), 667);
}

#[test]
fn test_try() {
fn try_result_some() -> Option<u8> {
Expand Down