Hi there,
I am currently struggling with a code that returning a closure. What I am trying to do describes as following.
fn init_work(param:Param) -> impl Fn() -> MyResult;
What I want to implement is make the function init_work
do some initialization works. And then move all the initialized states into the closure and return.
On the call site of init_work
, what I want to do is
let get_result = init_work(param);
// And then I can call get_result multiple times.
let actual_result_1 = get_result();
// .......
let actual_result_2 = get_result();
......
It works if the MyResult
doesn't have any reference to the closure. Unfortunately, I have to make reference to the closure to make a MyResult type. So I have to put some lifetime param to MyResult
fn init_work(param:Param) -> impl Fn() -> MyResult<'???>;
It seems reasonable to let MyResult has a lifetime parameter that doesn't outlive the lifetime of closure itself.
Each time the closure is called, it borrows a reference from the closure to the caller. And if the programmer try to drop the closure before all the result are drop, the compiler should be able to detect the error.
However, I don't know how to declare the closure's return value to have the lifetime of the closure itself.
If I have an object, it's quite easy to write the following code.
struct Context { ..... }
impl Context {
fn get_result<'a>(&'a self) -> MyResult<'a>;
}
fn init_work(param:Param) -> Context { ... }
let ctx = init_work(param);
let result = ctx.get_result();
However, I don't know how to do the same thing with a closure.
--- Update ---
I know the context struct is a work around. But my case is that I have too many states to capture and that is why I want a closure which can automatically hold the ownership of the states that would be used later.
So what I am asking is if there's an solution that I can implement the similar thing with closure without actually making a big context struct.
So I am wondering is there any workaround ?