Option syntax sugar: get some or return an error

I have the following code snippet:

match optional {
	Some(val) => val,
	None => return Err("some error"),

The function that this is part of returns a result. Is there some nice syntax sugar (probably in the std::option::Option) to get rid of the verbose Some(val) => val? Looking forward to your suggestions!
Edit: actually, I do want to return this match statement.

There's the let-else syntax:

let Some(foo) = optional else { 
    return Err("some error");

You can convert from Option to Result with the ok_or method, together with the try operator (?) to achieve the same result.


Does this still work well if I want to convert something like this?

if let Some(val) = optional1 {
} else if let Some(val) = optional2 {
} else {
  return Err("some err");

I would use unwrap_or together with my previous response in such case.

I'm not quite sure in which order you would use unwrap_or and ok_or, could you maybe provide a code example? Thanks!

unwrap_or is used to provide a fallback Option in this case, while ok_or is used to convert from Option to Result.

I can give you a code example in about 20 min. get I get back to the PC :smile:.

It's optional1.or(optional2).ok_or("some err")?;


This is really clean. I am using this now (I have function evaluations, so I thought it would be more efficient to lazily evaluate them):

Self::new(percentage, 0.0, 1.0)
	.or_else(|| Self::new(percentage, 0.0, 100.0))
	.ok_or_else(|| anyhow!("The percentage must be in the range of the specified minimum and maximum values"))?

The only part I am not sure about is the anyhow macro, as I don't know if the macro is a function call, which means I could also just use .ok_or(anyhow!("")). Anyone know about that?

If you're using anyhow you can use anyhow::Context; on visible scope and replace .ok_or_else(|| anyhow!("..."))? with .context("...")? which virtually is same code.


let val = optional.ok_or("some error")?;
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.