有没有办法从闭包内部的函数返回? [英] Is there any way to return from a function from inside a closure?
问题描述
我有以下简化代码:
fn f() -> i32 {
let a = some_result.unwrap_or_else(|_| {
return 1; // want to return this value from f <-------------
});
}
我想在这个特定的错误情况下从整个函数 f
返回值 1
但我不知道如何从闭包中做到这一点.
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.
如果我改为使用 match
表达式,它可以正常工作,如下所示:
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; },
};
}
但是,这会使代码变得冗长,因为我有简单的 Ok
匹配臂.
However, this makes the code verbose since I have the trivial Ok
match arm.
推荐答案
不,没有.
闭包是底层的方法(一种函数).您要求能够从任意深度嵌套的函数调用中退出父函数.这种非本地流控制通常已被证明对程序员的理智和程序维护极为不利.
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.
解决您的问题:
这篇关于有没有办法从闭包内部的函数返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!