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

编程入门 行业动态 更新时间:2024-10-26 02:37:09
本文介绍了有什么办法从闭包内部从函数返回吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下简化代码:

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

解决您的问题:

  • 如何解开结果好的还是从Err上的函数返回?
  • How do you unwrap a Result on Ok or return from the function on Err?

更多推荐

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

本文发布于:2023-11-14 09:05:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586793.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么办法   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!