i have troubles storing a function or closure in a global static variable to be accessed by multiple functions. In my snippet i create a static variable CALLBACK, which holds the reference to a closure. The closure should have access to the local variables in the main function.
type Callback<'a> = &'a mut dyn FnMut();
static mut CALLBACK: Option<Callback> = None;
fn main() {
let s = "Hello World";
let mut listener = || {
println!("{}",s)
};
unsafe {
CALLBACK = Some(&mut listener);
}
// call timer function for testing
timer_interrupt();
}
// method would be called by timer interrupt
fn timer_interrupt() {
unsafe {
CALLBACK.as_mut().map(|f| f());
}
}
Im getting two lifetime related errors:
error[E0597]: `s` does not live long enough
--> src/main.rs:10:19
|
9 | let mut listener = || {
| -- value captured here
10 | println!("{}",s)
| ^ borrowed value does not live long enough
...
14 | CALLBACK = Some(&mut listener);
| ------------- cast requires that `s` is borrowed for `'static`
...
19 | }
| - `s` dropped here while still borrowed
error[E0597]: `listener` does not live long enough
--> src/main.rs:14:21
|
14 | CALLBACK = Some(&mut listener);
| ^^^^^^^^^^^^^
| |
| borrowed value does not live long enough
| cast requires that `listener` is borrowed for `'static`
...
19 | }
| - `listener` dropped here while still borrowed
Is there a way to solve it by declaring the lifetime of the closure or is there another approach how to implement the functionality i need?
the replit snipped can be found here: https://replit.com/@lutzer/StaticClosure2#src/main.rs