根据Rust书,以下代码会导致closure may outlive the current function
错误:
use std::thread;
fn main() {
let x = 1;
thread::spawn(|| {
println!("x is {}", x);
});
}
考虑闭包何时以及如何比当前函数更活得更抽象;你能提供任何例子或规范吗?
最佳答案
由于您将闭包移动到一个线程中,并且线程可能比当前函数长寿(它们不会自动加入函数结束,使用 crossbeam
crate 来实现这种特性),它只是与将其移动到堆上相同。
如果您查看以下代码,您会发现将闭包移动到堆中并返回它是被禁止的。由于线程在借用方面基本相同,因此您不能在线程中引用任何内容。
fn foo() -> Box<FnOnce()> {
let x = 1;
Box::new(|| {
println!("x is {}", x);
})
}
fn main() {
let f = foo();
}
注意编译器在报错信息中给出了Problem的解决方案:
help: to force the closure to take ownership of `x` (and any other referenced variables), use the `move` keyword, as shown:
| Box::new(move || {
关于concurrency - 你能提供闭包比当前函数长寿的例子吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40970432/