Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 626
sshashank124 Avatar asked Aug 26 '18 15:08

sshashank124


People also ask

Can you name the return type of a closure function?

You have any kind of conditional in your function: Here, there isn't a single return type; each closure has a unique, un-namable type. You need to be able to name the returned type for any reason:

Is it possible to return a closure by value without boxes?

There is also an RFC ( its tracking issue) on adding unboxed abstract return types which would allow returning closures by value, without boxes, but this RFC was postponed. According to discussion in that RFC, it seems that some work is done on it recently, so it is possible that unboxed abstract return types will be available relatively soon.

What happens when you put a return statement at the end?

If you place a return statement at the end of the function, or anywhere else within the function, the function will immediately return to its caller.

Can you return a void function in C++?

Yes, you can certainly return from a function defined to return void. If you don’t place a return statement at the end, then the function will automatically return to its caller when execution reaches the end of the function. This is sometimes referred to as an implied return.


1 Answers

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:

  • How do you unwrap a Result on Ok or return from the function on Err?
like image 195
Shepmaster Avatar answered Sep 21 '22 07:09

Shepmaster