Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

unwrap

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?

like image 322
Matteo Monti Avatar asked Mar 11 '26 17:03

Matteo Monti


2 Answers

The typical workaround is to use unwrap_or_else():

let x_ok = x.unwrap_or_else(|_| panic!("Something went horribly wrong!"));
like image 131
user4815162342 Avatar answered Mar 14 '26 09:03

user4815162342


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") };
like image 27
cafce25 Avatar answered Mar 14 '26 10:03

cafce25



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!