Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...