libcore/Result - RFC#1119 Add an 'expect' method to Result
This commit is contained in:
parent
172cd83490
commit
0937c10f3c
3 changed files with 34 additions and 0 deletions
|
|
@ -731,6 +731,26 @@ impl<T, E: fmt::Debug> Result<T, E> {
|
|||
panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Unwraps a result, yielding the content of an `Ok`.
|
||||
///
|
||||
/// Panics if the value is an `Err`, with a panic message including the
|
||||
/// passed message, and the content of the `Err`.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```{.should_panic}
|
||||
/// #![feature(result_expect)]
|
||||
/// let x: Result<u32, &str> = Err("emergency failure");
|
||||
/// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable(feature = "result_expect", reason = "newly introduced")]
|
||||
pub fn expect(self, msg: &str) -> T {
|
||||
match self {
|
||||
Ok(t) => t,
|
||||
Err(e) => panic!("{}: {:?}", msg, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@
|
|||
#![feature(cell_extras)]
|
||||
#![feature(iter_empty)]
|
||||
#![feature(iter_once)]
|
||||
#![feature(result_expect)]
|
||||
|
||||
extern crate core;
|
||||
extern crate test;
|
||||
|
|
|
|||
|
|
@ -137,3 +137,16 @@ pub fn test_unwrap_or_else_panic() {
|
|||
let bad_err: Result<isize, &'static str> = Err("Unrecoverable mess.");
|
||||
let _ : isize = bad_err.unwrap_or_else(handler);
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
pub fn test_expect_ok() {
|
||||
let ok: Result<isize, &'static str> = Ok(100);
|
||||
assert_eq!(ok.expect("Unexpected error"), 100);
|
||||
}
|
||||
#[test]
|
||||
#[should_panic(expected="Got expected error: \"All good\"")]
|
||||
pub fn test_expect_err() {
|
||||
let err: Result<isize, &'static str> = Err("All good");
|
||||
err.expect("Got expected error");
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue