Temporary value dropped while borrowed using Closure

To solve this error
"the size for values of type (dyn std::ops::Fn() + 'static) cannot be known at compilation time"

I added on_click: Option<&'static dyn Fn() -> ()>

But now I am unsure how to solve
"temporary value dropped while borrowed"

fn main(){
let initial_state = 5;
fn handler(val: i32) {
       val + 1;
       ()
   }
   
let props = Props { on_click: Some(&|| handler(initial_state))};
}

struct Props {
   on_click: Option<&'static dyn Fn() -> ()>
}

How do I make initial_state live long enough?

By using &'static you are telling the compiler that the closure must be an immutable compile time constant, so you can't store a local variable such as initial_state inside it. Use a Box instead.

struct Props {
   on_click: Option<Box<dyn Fn() -> ()>>
}
1 Like

You will probably also need to annotaye your closure with move

move || handler(initial_state)

If you want to see how closures are desugared, you can read my blog on the subject:

1 Like

@RustyYato Thank you, I will read your blog on closures. I am working with the wasm crate right now and am running into many issues regarding closures and lifetime's.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.