首页 > 解决方案 > 在`main`中指定值的静态生命周期,以便回调可以借用

问题描述

我有一个变量用于跟踪由处理程序闭包更新的状态。类似于以下内容:

fn main() {
    let val = 1;
    add_handler(|| val += 1);
    println!("{}", val);
}

add_handler函数在另一个库中声明并具有类型

fn add_handler<F>(listener: F) where F: FnMut() + 'static

当我尝试编译它时,我收到一个错误:

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);
  |                 ^^^^^^^

因为valmain我知道它会在程序的整个长度内被声明,但编译器显然不知道这一点,我不能val进入闭包,因为我以后需要使用它。

这类似于“错误:闭包可能超过当前函数”,但它不会超过它,但我无法摆脱'static定义中的生命周期,add_handler因为我不控制定义。

这不是Closure 的副本,可能会比当前函数寿命更长,因为我无法val进入闭包。

我可以val按照如何创建一个全局的、可变的单例来创建一个全局原子?,但似乎应该有一种更简洁、更惯用的方式来告诉编译器它的val寿命足够长。

我该怎么做呢?

标签: rust

解决方案


推荐阅读