I have a variable that I am using to keep track of state which is updated by a handler closure. Something like the following:
fn main() {
let val = 1;
add_handler(|| val += 1);
println!("{}", val);
}
The add_handler
function is declared in another library and has the type
fn add_handler<F>(listener: F) where F: FnMut() + 'static
When I try to compile this, I get an error:
error[E0373]: closure may outlive the current function, but it borrows `val`, which is owned by the current function
--> src/main.rs:3:16
|
3 | add_handler(|| val += 1);
| ^^ --- `val` is borrowed here
| |
| may outlive borrowed value `val`
help: to force the closure to take ownership of `val` (and any other referenced variables), use the `move` keyword
|
3 | add_handler(move || val += 1);
| ^^^^^^^
Because val
is declared in main
I know it will live for the entire length of the program, but the compiler apparently doesn't know this, and I can't move val
into the closure because I need to use it later.
This is similar to "error: closure may outlive the current function" but it will not outlive it but I can't get rid of the 'static
lifetime in the definition of add_handler
because I don't control the definition.
This is not a duplicate of Closure may outlive the current function because I can't move val
into the closure.
I could make val
a global atomic as per How do I create a global, mutable singleton?, but it seems like there should a cleaner more idiomatic way to tell the compiler that val
will live long enough.
How do I do this?