Skip to content

Commit dddb10c

Browse files
committed
libcore/Result - Add an expect method that prints a message and the Err value
1 parent 8767e97 commit dddb10c

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/libcore/result.rs

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

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

0 commit comments

Comments
 (0)