相关疑难解决方法(0)

Future 生成器闭包时出错:捕获的变量无法转义“FnMut”闭包主体

我想创建一个简单的 websocket 服务器。我想处理传入的消息并发送响应,但收到错误:

error: captured variable cannot escape `FnMut` closure body
  --> src\main.rs:32:27
   |
32 |       incoming.for_each(|m| async {
   |  _________________________-_^
   | |                         |
   | |                         inferred to be a `FnMut` closure
33 | |         match m {
34 | |             // Error here...
35 | |             Ok(message) => do_something(message, db, &mut outgoing).await,
36 | |             Err(e) => panic!(e)
37 | |         }
38 | |     }).await;
   | |_____^ returns a reference to a captured variable which escapes the closure …
Run Code Online (Sandbox Code Playgroud)

rust async-await

9
推荐指数
1
解决办法
9840
查看次数

“由于在生成器中使用而发生移动”错误在 Rust 中意味着什么?

我有关于发电机的这个问题:

use tokio::runtime::Runtime;
use tokio::task::JoinHandle;
use std::sync::Arc;

pub fn run(f: Box<dyn Fn() -> Result<(), ()> + Send>) {
    f();
}

fn main() {
    let x = Arc::new(0);
    run(Box::new(move ||{
        let rt = Runtime::new().unwrap();
        let _t = rt.block_on(async move {
            let y = x;
        });
        Ok(())
    }));
}
Run Code Online (Sandbox Code Playgroud)

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=de28ecf9e5baf6a017cd6a5230d74d7b

错误:

error[E0507]: cannot move out of `x`, a captured variable in an `Fn` closure
  --> src/main.rs:13:41
   |
10 |       let x = Arc::new(0);
   |           - captured outer variable
...
13 |           let …
Run Code Online (Sandbox Code Playgroud)

smart-pointers move-semantics rust

1
推荐指数
1
解决办法
213
查看次数