1

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Kwarrtz
  • 2,693
  • 15
  • 24
  • 1
    *I know it will live for the entire length of the program* — It actually **won't**, which is why you get that error. The Rust `main` function exits *before* the OS `main` function does. Threads can and do continue running after the Rust `main` exits. This doesn't even cover the detail of destruction order of multiple variables in the same scope. – Shepmaster Jul 07 '18 at 19:36
  • @Shepmaster That question does seem to include all of the salient points of this one. I'm fine with this being marked as a duplicate. – Kwarrtz Jul 07 '18 at 19:54

0 Answers0