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.
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:
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With