Skip to content

Commit a54a809

Browse files
committed
Auto merge of rust-lang#25359 - thepowersgang:result-expect-2, r=alexcrichton
As it says in the title. I've added an `expect` method to `Result` that allows printing both an error message (e.g. what operation was attempted), and the error value. This is separate from the `unwrap` and `ok().expect("message")` behaviours.
2 parents 7d04623 + 0937c10 commit a54a809

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

src/libcore/result.rs

+20
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,26 @@ impl<T, E: fmt::Debug> Result<T, E> {
731731
panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
732732
}
733733
}
734+
735+
/// Unwraps a result, yielding the content of an `Ok`.
736+
///
737+
/// Panics if the value is an `Err`, with a panic message including the
738+
/// passed message, and the content of the `Err`.
739+
///
740+
/// # Examples
741+
/// ```{.should_panic}
742+
/// #![feature(result_expect)]
743+
/// let x: Result<u32, &str> = Err("emergency failure");
744+
/// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
745+
/// ```
746+
#[inline]
747+
#[unstable(feature = "result_expect", reason = "newly introduced")]
748+
pub fn expect(self, msg: &str) -> T {
749+
match self {
750+
Ok(t) => t,
751+
Err(e) => panic!("{}: {:?}", msg, e),
752+
}
753+
}
734754
}
735755

736756
#[stable(feature = "rust1", since = "1.0.0")]

src/libcoretest/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#![feature(cell_extras)]
2929
#![feature(iter_empty)]
3030
#![feature(iter_once)]
31+
#![feature(result_expect)]
3132

3233
extern crate core;
3334
extern crate test;

src/libcoretest/result.rs

+13
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,16 @@ pub fn test_unwrap_or_else_panic() {
137137
let bad_err: Result<isize, &'static str> = Err("Unrecoverable mess.");
138138
let _ : isize = bad_err.unwrap_or_else(handler);
139139
}
140+
141+
142+
#[test]
143+
pub fn test_expect_ok() {
144+
let ok: Result<isize, &'static str> = Ok(100);
145+
assert_eq!(ok.expect("Unexpected error"), 100);
146+
}
147+
#[test]
148+
#[should_panic(expected="Got expected error: \"All good\"")]
149+
pub fn test_expect_err() {
150+
let err: Result<isize, &'static str> = Err("All good");
151+
err.expect("Got expected error");
152+
}

0 commit comments

Comments
 (0)