未验证 提交 921a8200 编写于 作者: Y Yuki Okushi 提交者: GitHub

Rollup merge of #83421 - faern:add-into-err, r=joshtriplett

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

Equivalent of #66045 but for the inverse situation where `T: Into<!>` rather than `E: Into<!>`.

I'm using the same feature gate name. I can't see why one of these methods would be OK to stabilize but not the other.

Tracking issue: #61695
......@@ -1167,6 +1167,42 @@ pub fn into_ok(self) -> T {
}
}
#[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>`.
///
......
......@@ -225,6 +225,28 @@ fn infallible_op2() -> Result<isize, MyNeverToken> {
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> {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册