How can I return from a closure argument

As below:

fn foo() -> Result<(), &str> {
    let bar = some_fn_that_returns_option()
        .unwrap_or_else(|| {
            //I wanna return the foo() with some error message here
            //How can I do it?
            //I know a match/if-let can do the same thing, 
            //but thats a wholy different code structure!
            });
    Ok(())
}

The last expression is what will be returned from the closure.

You cannot return from foo from within the closure.
Closures are essentially their own functions and control flow is local to that closure, not the surrounding one.

Use another construct: match, if-let, mapping to Ok and Err values, ...

3 Likes

Thanks much.

A nice way is to use let..else:

let Some(bar) = some_fn_that_returns_option() else { return Err("error!") };

But you can also "return from foo" from within a closure if you use the ? operator, and it's even shorter actually:

let bar = some_fn_that_returns_option().ok_or_else(|| "error!")?;
// or even .ok_or("error")? if it's just a simple constant

Note that closures can be moved/cloned/copied,[1] for example passed to other functions, sent to other threads, and generally executed in a different control flow context than the definition site.

In fact, that's what you're doing when you pass your closure to the unwrap_or_else method.


  1. depending on their captures ↩ī¸Ž

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.