首页 > 解决方案 > 为什么我需要克隆一个移动的变量?

问题描述

为什么我需要克隆tx?我移动了它。我不能再在我的主线程中使用它了。

use std::sync::mpsc::{channel, Sender};

fn main() {
    let (tx, _rx) = channel();

    std::thread::spawn(move || {
        takes_closure(|| Foo { sender: tx });
    });
}

struct Foo {
    sender: Sender<()>,
}

fn takes_closure(_: impl FnMut() -> Foo) {}

操场

这有错误:

error[E0507]: cannot move out of captured variable in an `FnMut` closure
 --> src/main.rs:7:40
  |
4 |     let (tx, _rx) = channel();
  |          -- captured outer variable
...
7 |         takes_closure(|| Foo { sender: tx });
  |                                        ^^ cannot move out of captured variable in an `FnMut` closure

标签: rustmove

解决方案


推荐阅读