Is there a macro that will convert an error into a panic, similar to the try
macro? Do I need to define my own?
For example I'd like to panic if a unit test can't open a file. My current workaround is this:
macro_rules! tryfail {
($expr:expr) => (match $expr {
result::Result::Ok(val) => val,
result::Result::Err(_) => panic!(stringify!($expr))
})
}
#[test]
fn foo() {
let c = tryfail!(File::open(...));
}
This is exactly what the methods Result::unwrap
and Result::expect
do.
I know you are asking for a macro, but I think your use case can be fulfilled with the unwrap
method:
#[test]
fn foo() {
let c = File::open(...).unwrap();
// vs
let c = tryfail!(File::open(...));
}
Note that in code that is not test, it's more idiomatic to use expect
.
If you really want a macro, you can write one using unwrap
.