Skip to content

Commit e520b77

Browse files
author
Clar Charr
committed
expect_err for Result.
1 parent 7bffede commit e520b77

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

src/libcore/result.rs

+25
Original file line numberDiff line numberDiff line change
@@ -798,6 +798,31 @@ impl<T: fmt::Debug, E> Result<T, E> {
798798
Err(e) => e,
799799
}
800800
}
801+
802+
/// Unwraps a result, yielding the content of an `Err`.
803+
///
804+
/// # Panics
805+
///
806+
/// Panics if the value is an `Ok`, with a panic message including the
807+
/// passed message, and the content of the `Ok`.
808+
///
809+
/// # Examples
810+
///
811+
/// Basic usage:
812+
///
813+
/// ```{.should_panic}
814+
/// # #![feature(result_expect_err)]
815+
/// let x: Result<u32, &str> = Ok(10);
816+
/// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
817+
/// ```
818+
#[inline]
819+
#[unstable(feature = "result_expect_err", issue = "39041")]
820+
pub fn expect_err(self, msg: &str) -> E {
821+
match self {
822+
Ok(t) => unwrap_failed(msg, t),
823+
Err(e) => e,
824+
}
825+
}
801826
}
802827

803828
impl<T: Default, E> Result<T, E> {

src/libcoretest/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
#![feature(nonzero)]
2424
#![feature(rand)]
2525
#![feature(raw)]
26+
#![feature(result_expect_err)]
2627
#![feature(sip_hash_13)]
2728
#![feature(slice_patterns)]
2829
#![feature(step_by)]

src/libcoretest/result.rs

+13
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,19 @@ pub fn test_expect_err() {
151151
err.expect("Got expected error");
152152
}
153153

154+
155+
#[test]
156+
pub fn test_expect_err_err() {
157+
let ok: Result<&'static str, isize> = Err(100);
158+
assert_eq!(ok.expect_err("Unexpected ok"), 100);
159+
}
160+
#[test]
161+
#[should_panic(expected="Got expected ok: \"All good\"")]
162+
pub fn test_expect_err_ok() {
163+
let err: Result<&'static str, isize> = Ok("All good");
164+
err.expect_err("Got expected ok");
165+
}
166+
154167
#[test]
155168
pub fn test_iter() {
156169
let ok: Result<isize, &'static str> = Ok(100);

0 commit comments

Comments
 (0)