From e520b77efed718dd6ba4509f5a8d5860ad80e660 Mon Sep 17 00:00:00 2001 From: Clar Charr Date: Tue, 10 Jan 2017 22:17:47 -0500 Subject: [PATCH] expect_err for Result. --- src/libcore/result.rs | 25 +++++++++++++++++++++++++ src/libcoretest/lib.rs | 1 + src/libcoretest/result.rs | 13 +++++++++++++ 3 files changed, 39 insertions(+) diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 99c407e5273..f02df88bb2e 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -798,6 +798,31 @@ impl Result { 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 = 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 Result { diff --git a/src/libcoretest/lib.rs b/src/libcoretest/lib.rs index d12616a97a6..ee47b510ee0 100644 --- a/src/libcoretest/lib.rs +++ b/src/libcoretest/lib.rs @@ -23,6 +23,7 @@ #![feature(nonzero)] #![feature(rand)] #![feature(raw)] +#![feature(result_expect_err)] #![feature(sip_hash_13)] #![feature(slice_patterns)] #![feature(step_by)] diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index bc2cd8bbfc6..4c5f19dee12 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -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 = Ok(100);