rust Option ok_or without unwrap()? looking for value_or function

163 Views Asked by At

I am making a function that returns a Result<MyValue, &str> because there are so many Ok Results, and Some Option that need unwrapping inside my function. I wanted to use ?, be able to return Result errors, and not live inside a 20 layer unwrapped if let Some(a) = b and if let Ok(a) = b function. as such I have been using

fn from_ui(ui:&HtmlElement) -> Result<MyValue, &str> 
{
  let a = ui.get_attribute("data-my").ok_or("Value. Error 0");
  let a = a.unwrap(); 
  ... 
}

my issue is that I need to do 'let a = a.unwrap()' because ok_or returns the Ok Result, and not the value inside of the Ok result. Is there a function I can use that is just like .value_or("Value. Error Code 0")

I find the additional unwrap tedious. It also basically doubles the size of the function without adding any value. I've done .ok_or("Value. Error 0").unwrap() to reduce the number of lines of code and that does work.

I have also looked at all the unwrap_or... variations but those appear to return a default value to the left-hand-side variable instead of returning from the function with an Error string. In swift this is known as a guard I would not like to use any crates if possible.

0

There are 0 best solutions below