首页 > 解决方案 > 如何在堆上拥有一个独特的 lambda 实例,以便在不同的消费者之间共享?

问题描述

我似乎无法规避运行 lambda 将其移出共享引用的事实。

use std::rc::Rc;

fn run_my_fn(my_fn: Rc<impl FnOnce() -> u32>) -> u32 {
    (*my_fn)(); // cannot move out of an `Rc`
    (my_fn.as_ref())() // cannot move out of a shared reference
}

fn main() {
    let my_fn = Rc::new(|| { 123 as u32 });    
    let _res = run_my_fn(my_fn.clone()); 
}

操场

error[E0507]: cannot move out of an `Rc`
 --> src/main.rs:4:5
  |
4 |     (*my_fn)();
  |     ^^^^^^^^ move occurs because value has type `impl FnOnce() -> u32`, which does not implement the `Copy` trait

error[E0507]: cannot move out of a shared reference
 --> src/main.rs:5:5
  |
5 |     (my_fn.as_ref())() 
  |     ^^^^^^^^^^^^^^^^ move occurs because value has type `impl FnOnce() -> u32`, which does not implement the `Copy` trait

标签: lambdarust

解决方案


推荐阅读