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

Clone a String for an async move closure in Rust

有什么方法可以克隆 futures::streamasync move 闭包的值吗?

我正在使用未来的 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`

如果这是一个循环,我会在每次迭代中克隆 as,然后将这些克隆移动到一个闭包中,这里有没有办法做这样的事情?

您可以简单地在 async move 块之前克隆 a

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