concurrency - 你能提供闭包比当前函数长寿的例子吗?

标签 concurrency rust closures

根据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/

相关文章:

java - 用餐哲学家、Java 和监视器 : IllegalMonitorStateException

java - 面向对象设计和在抽象父类(super class)中初始化静态成员

javascript - 具有 close 的库无法根据其构造函数创建新对象

swift - 如何将一个闭包附加到另一个闭包?

将最后一个任务添加到 BlockingQueue 并丢弃其他任务的 Java 线程池

rust - 为什么在匹配结果中使用引用会导致 "cannot move out of dereference"?

rust - 有没有办法同时以不可变和可变的方式借用 RefCell?

generics - 限制 Rust 结构体的泛型参数进行反序列化

swift 泛型 : Custom closure with multiple arguments for filter function

java - 多路复用 Java 的 LinkedBlockingQueue