Idiomatic way to early-return if Option is None?

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.

1 Like

You can use let else like this:

let Some(result) = compute(input) else {
    return String::from("missing");
};
15 Likes

In the code calling that function how do you differentiate the missing case from the normal case?

I don't. Both cases return a string and I display them in both cases. the None-case would just say "Missing"

Oh yeah. I was missing the "else" part. Thanks!

Wouldn't it be simpler to use the ? operator ? and your calling code would then be foo(...).unwrap_or_else(|| "Missing".to_owned())

The body of your function would be simpler, the missing case clearly addressed by the caller.

4 Likes

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.

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.