在 Rust 中克隆用于异步移动闭包的字符串

And*_*nov 5 asynchronous future stream rust

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

我正在使用未来的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;
}
Run Code Online (Sandbox Code Playgroud)

这里的错误:

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
Run Code Online (Sandbox Code Playgroud)

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`
Run Code Online (Sandbox Code Playgroud)

如果它是一个循环,我只需a在每次迭代中克隆 s ,并将这些克隆移动到闭包内,有没有办法在这里做这样的事情?

Ibr*_*med 12

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

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