Specifying static lifetime of value in `main` so callback can borrow [duplicate]

与世无争的帅哥 提交于 2021-01-29 10:24:37

问题


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?

来源:https://stackoverflow.com/questions/51226135/specifying-static-lifetime-of-value-in-main-so-callback-can-borrow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!