你能提供闭包超过当前功能的任何例子吗?

ena*_*naJ 0 concurrency closures rust

基于Rust书,以下代码可能导致closure may outlive the current function错误:

use std::thread;

fn main() {
    let x = 1;
    thread::spawn(|| {
        println!("x is {}", x);
    });
}
Run Code Online (Sandbox Code Playgroud)

考虑闭包何时以及如何比当前函数更长时间是抽象的; 你能提供任何例子或规格吗?

oli*_*obk 5

由于您将闭包移动到一个线程中,并且线程可能比当前函数更长(它们不会自动连接到函数端,使用crossbeamcrate来实现这种特性),它与在堆上移动它一样.

如果您查看以下代码段,您可以看到禁止将闭包移动到堆并返回它.由于线程在借用方面基本相同,因此您无法在线程中引用任何内容.

fn foo() -> Box<FnOnce()> {
    let x = 1;
    Box::new(|| {
        println!("x is {}", x);
    })
}

fn main() {
    let f = foo();
}
Run Code Online (Sandbox Code Playgroud)

请注意,编译器在错误消息中提供了问题的解决方案:

help: to force the closure to take ownership of `x` (and any other referenced variables), use the `move` keyword, as shown:
  |     Box::new(move || {
Run Code Online (Sandbox Code Playgroud)