Skip to content

Commit

Permalink
Auto merge of #38982 - clarcharr:expect_err, r=aturon
Browse files Browse the repository at this point in the history
expect_err for Result.

This adds an `expect_err` method to `Result`. Considering how `unwrap_err` already exists, this seems to make sense. Inconsistency noted in Manishearth/rust-clippy#1435.
  • Loading branch information
bors committed Jan 14, 2017
2 parents d4b063d + e520b77 commit 2f9dedb
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/libcore/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,31 @@ impl<T: fmt::Debug, E> Result<T, E> {
Err(e) => e,
}
}

/// Unwraps a result, yielding the content of an `Err`.
///
/// # Panics
///
/// Panics if the value is an `Ok`, with a panic message including the
/// passed message, and the content of the `Ok`.
///
/// # Examples
///
/// Basic usage:
///
/// ```{.should_panic}
/// # #![feature(result_expect_err)]
/// let x: Result<u32, &str> = Ok(10);
/// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
/// ```
#[inline]
#[unstable(feature = "result_expect_err", issue = "39041")]
pub fn expect_err(self, msg: &str) -> E {
match self {
Ok(t) => unwrap_failed(msg, t),
Err(e) => e,
}
}
}

impl<T: Default, E> Result<T, E> {
Expand Down
1 change: 1 addition & 0 deletions src/libcoretest/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#![feature(nonzero)]
#![feature(rand)]
#![feature(raw)]
#![feature(result_expect_err)]
#![feature(sip_hash_13)]
#![feature(slice_patterns)]
#![feature(step_by)]
Expand Down
13 changes: 13 additions & 0 deletions src/libcoretest/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,19 @@ pub fn test_expect_err() {
err.expect("Got expected error");
}


#[test]
pub fn test_expect_err_err() {
let ok: Result<&'static str, isize> = Err(100);
assert_eq!(ok.expect_err("Unexpected ok"), 100);
}
#[test]
#[should_panic(expected="Got expected ok: \"All good\"")]
pub fn test_expect_err_ok() {
let err: Result<&'static str, isize> = Ok("All good");
err.expect_err("Got expected ok");
}

#[test]
pub fn test_iter() {
let ok: Result<isize, &'static str> = Ok(100);
Expand Down

0 comments on commit 2f9dedb

Please sign in to comment.