有没有办法为
我正在使用 future 的
futures::stream
的 async 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
并将这些克隆移动到闭包内部,是否有一种方法可以在这里做类似的事情?