I seem to repeat code that needs to handle a value which is an Option.
If the value is None I'd like to return immediately from the function, if the value is Some() I'd like to continue.
I have many solution, none of them seem to be idiomatic.
For example this one that has the annoying unwrap there.
let result = compute(input);
if result.is_none() {
return String::from("Missing");
}
let data = result.unwrap();
// process data:
Or this with a match
let result = compute(input);
let data = match result {
None => return String::from("Missing"),
Some(data) => data,
};
// process data:
Or this with the match in a macro:
macro_rules! ok_or_return {
($cond: expr, $result: expr) => {
match $cond {
None => return $result,
Some(data) => data,
}
};
}
let result = compute(input);
let data = ok_or_return!(result, String::from("Missing"));
// process data:
I am quite sure there is a more idiomatic way, but so far could not figure it out.
Or a slight variation on that; have a utility function fn do_the_thing_opt(…) -> Option<String> containing the body of the function and using ? to return None early, and then make the original function fn do_the_thing(...) -> String { do_the_thing_opt(…).unwrap_or_else(|| "Missing".to_owned()) }
That keeps the original signature, makes it easy to refactor if you later need to distinguish None from Some, and allows you to use ? for clarity.