在 Rust 中为异步移动闭包克隆一个字符串

5
有没有办法为 futures::streamasync move 闭包克隆值?
我正在使用 future 的 for_each_concurrent 我的代码大致如下:
async fn foo() {
    use futures::stream::{self, StreamExt};

    let a: String = String::new();

    let stream = stream::once(async { 42 });

    stream
        .for_each_concurrent(None, |stream_item| async move {
            println!("{}", a);
            println!("{}", stream_item);
        })
        .await;
}

这里的错误:

error[E0507]: cannot move out of `a`, a captured variable in an `FnMut` closure
  --> src/main.rs:9:61
   |
4  |       let a: String = String::new();
   |           - captured outer variable
...
9  |           .for_each_concurrent(None, |stream_item| async move {
   |  _____________________________________________________________^
10 | |             println!("{}", a);
   | |                            -
   | |                            |
   | |                            move occurs because `a` has type `String`, which does not implement the `Copy` trait
   | |                            move occurs due to use in generator
11 | |             println!("{}", stream_item);
12 | |         })
   | |_________^ move out of `a` occurs here

我必须使用move,因为:

error[E0373]: async block may outlive the current function, but it borrows `stream_item`, which is owned by the current function
  --> src/main.rs:9:56
   |
9  |           .for_each_concurrent(None, |stream_item| async {
   |  ________________________________________________________^
10 | |             println!("{}", a);
11 | |             println!("{}", stream_item);
   | |                            ----------- `stream_item` is borrowed here
12 | |         })
   | |_________^ may outlive borrowed value `stream_item`

如果这是一个循环,我只需在每次迭代中克隆 a 并将这些克隆移动到闭包内部,是否有一种方法可以在这里做类似的事情?

1个回答

12
您可以在 async move 代码块前克隆 a
stream
    .for_each_concurrent(None, |stream_item| {
        let a = a.clone();
        async move {
            println!("{}", a);
            println!("{}", stream_item);
        }
    })
    .await;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接