【问题标题】:Can you provide any example where the closure outlives the current function?你能提供任何闭包比当前函数寿命更长的例子吗?
【发布时间】:2016-12-05 08:57:41
【问题描述】:
根据 Rust 书,以下代码可能会导致 closure may outlive the current function 错误:
use std::thread;
fn main() {
let x = 1;
thread::spawn(|| {
println!("x is {}", x);
});
}
考虑闭包何时以及如何超过当前函数发生是抽象的;你能提供任何例子或规范吗?
【问题讨论】:
标签:
concurrency
rust
closures
【解决方案1】:
由于您将闭包移动到线程中,并且线程可能会比当前函数寿命更长(它们不会自动加入函数结束,请使用 crossbeam 板条箱来实现此类功能),这与移动它相同堆。
如果您查看以下代码,您可以看到将闭包移动到堆并返回它是被禁止的。由于线程在借用方面基本相同,因此您不能在线程中引用任何内容。
fn foo() -> Box<FnOnce()> {
let x = 1;
Box::new(|| {
println!("x is {}", x);
})
}
fn main() {
let f = foo();
}
注意编译器在错误信息中给出了问题的解决方案:
help: to force the closure to take ownership of `x` (and any other referenced variables), use the `move` keyword, as shown:
| Box::new(move || {