sshashank124
sshashank124

Reputation: 32189

Is there any way to return from a function from inside a closure?

I have the following simplified code:

fn f() -> i32 {
    let a = some_result.unwrap_or_else(|_| {
        return 1; // want to return this value from f <-------------
    });
}

I want to return the value 1 from the whole function f in this specific error case but I can't figure out how to do it from within a closure.

If I instead use a match expression, it works fine as follows:

fn f() -> i32 {
    let a = match some_result {
        Ok(result) => result,
        Err(_)     => { return 1; },
    };
}

However, this makes the code verbose since I have the trivial Ok match arm.

Upvotes: 39

Views: 12740

Answers (3)

Fee
Fee

Reputation: 776

These days, this specific example is also solveable with pattern matching:

fn f(some_result: Result<i32, ()>) -> i32 {
    let Ok(a) = some_result else {
        return 1; // can actually return this value from f <-------------
    });
    a
}

Upvotes: 3

InssaGwajang
InssaGwajang

Reputation: 59

I would like to show you a trick.

If you make a mutable valuable for the exception case, you can set the value in the closure. And then, you could make the function returning specific value.

fn f() -> i32 {
    let mut invalid: bool = false; // + It is for the exception case

    let a = some_result.unwrap_or_else(|_| {
        // return 1; // want to return this value from f <-------------
        invalid = true; // + If the case is exceptional,
    });

    if invalid { // + If the value is marked, return specific value
        return 1;
    }
    ...
}

Because a closure is a method, there is no way exactly. I would like to comment that it is just a trick.

Upvotes: 5

Shepmaster
Shepmaster

Reputation: 430624

No, there is not.

A closure is a method (a kind of function) under the hood. You are asking for the ability to exit a parent function from an arbitrarily deeply nested function call. Such non-local flow control has generally proven to be extremely bad for programmer sanity and program maintenance.


To solve your problem:

Upvotes: 32

Related Questions