Return from a function if `Option<T>` is not `None`

Hello,
I want to return early from a function if an Option<T> is not None.
I'm missing methods to work with Option::None like Result has (expect_err, unwrap_err, etc).
I know this is possible with x.ok_or(()).err().ok_or(...)?, but that's completely unreadable.
Am I looking over a method in the documentation, should I take a completely other approach, or is this not easily possible?

You can just do

if let Some(value) = option {
    return value;
}

If you show us an actual, existing function to refactor and its context, we might be able to offer more useful help.

4 Likes

That makes sense. I'm in love with rusts method chaining, and I didn't realize if let was also possible here. Thanks!

If you look the the methods' source code (e.g. via docs.rs), you can see they are all implemented via a simple match. You should keep that in mind when trying to find an apparently complicated solution via combinators: it might be simpler to just spell it out using match (or in this case if let, which is just syntactic sugar for match).

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.