rust - 在`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);
| ^^^^^^^
因为val
在main
我知道它会在程序的整个长度内被声明,但编译器显然不知道这一点,我不能val
进入闭包,因为我以后需要使用它。
这类似于“错误:闭包可能超过当前函数”,但它不会超过它,但我无法摆脱'static
定义中的生命周期,add_handler
因为我不控制定义。
这不是Closure 的副本,可能会比当前函数寿命更长,因为我无法val
进入闭包。
我可以val
按照如何创建一个全局的、可变的单例来创建一个全局原子?,但似乎应该有一种更简洁、更惯用的方式来告诉编译器它的val
寿命足够长。
我该怎么做呢?
解决方案
推荐阅读
- c++ - 访问私人课程
- python - 局部变量 'i' 可能在赋值之前被引用
- c# - 创建一个在线程及其所有子线程之间共享的值
- c# - Xamarin窗体IOS中System.Exception+ExceptionMessageKind.OutOfMemory如何处理?
- node.js - 我无法在我的获取请求中从我的中间件获取有效负载中的用户 ID
- c# - 对撞机没有检测到?
- azure - Azure 应用服务与 VM 中的 SQL Server 集成
- elasticsearch - 如何在elasticsearch中获取带有条件的桶数?
- html - 在选择了同一组中的其他单选按钮后,我们如何重置单选按钮
- node.js - Node.js 集群 - 为什么脚本在没有明显原因的情况下多次运行?