Is This The Most Succinct Way of Doing This?

This is something I find myself doing a lot. Is there a more succinct way to do this?

let variable = if let Some(variable) = variable {
    variable
} else {
    return;
};

I know I could do a macro, and sometimes I might opt for that, but is there another way I'm missing?

When the function returns a result or an option, I can use the ? operator to do the unwrap, but what if the function returns ()?

3 Likes

There's a new let else feature coming soon which will let you write:

let Some(variable) = option else { return; }
10 Likes

Macro is the right way to do it. You can also wrap the code in an inner function:

fn outer() {
    fn inner() -> Option<()> {
        variable?;
        Some(())
    }
    inner();
}
3 Likes

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.