有什么办法从闭包内部从函数返回吗?

问题描述:

我有以下简化代码:

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

我要返回值 1 $在这种特定的错误情况下,来自整个函数 f 的c $ c>,但我无法从封闭中找出方法。

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.

解决您的问题:

  • How do you unwrap a Result on Ok or return from the function on Err?