4

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(...));
}
laktak
  • 57,064
  • 17
  • 134
  • 164

1 Answers1

6

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.

malbarbo
  • 10,717
  • 1
  • 42
  • 57
  • 4
    Note that [`Option::expect`](http://doc.rust-lang.org/core/option/enum.Option.html#method.expect) and [`Option::unwrap`](http://doc.rust-lang.org/core/option/enum.Option.html#method.unwrap) also exist. – Shepmaster Jun 08 '16 at 12:51