Alternative to `unwrap()` when `T` does not implement `Debug`

1.5k Views Asked by At

I am aware that x.unwrap() when x: Result<T, E> does not work when E does not implement Debug: unwrap() would need to print out the Err variant in case x.is_err() but it cannot. Sometimes, however, especially in tests, I do need to get my hands on the Ok value. I assumed x.expect() would do the trick, as I am the one that specifies the message upon failure. And yet, for some reason I don't completely understand, expect(), too, requires E: Debug. This means that I always end up taking the verbose, repetitive way:

   let x_ok = match x {
      Ok(x_ok) => x_ok,
      Err(_) => panic!("Something went horribly wrong!"),
   }

I cannot imagine there wouldn't be a more standardised solution to this problem, and yet I struggle to find one. How does one quickly get_ok_or_panic if the Err type of a Result does not implement Debug?

2

There are 2 best solutions below

2
cafce25 On BEST ANSWER

Idiomatic code would just forward the error:

fn do_it() -> Result<(), E> {
   let x_ok = x_ok?;
   // work with x_ok
   Ok(())
}

or handle the error gracefully where possible:

let x_ok = x_ok.unwrap_or(sane_default);

If neither is an option and you absolutely have to panic you can use let … else:

let Ok(x_ok) = x_ok else { panic!("Something went horribly wrong") };
2
user4815162342 On

The typical workaround is to use unwrap_or_else():

let x_ok = x.unwrap_or_else(|_| panic!("Something went horribly wrong!"));