I'm trying to use scan method from StreamExt. It works perfectly if I have no async block.
use futures::{stream, StreamExt};
#[tokio::main]
async fn main() {
stream::iter(1..10)
.scan(0, |s, i| {
*s += i;
futures::future::ready(Some(*s))
})
.for_each(|x| async move {
println!("{:?}", x);
})
.await;
}
But if I do have async block, it doesn't compile.
use futures::{stream, StreamExt};
#[tokio::main]
async fn main() {
stream::iter(1..10)
.scan(0, |s, i| async move {
*s += i;
Some(*s)
})
.for_each(|x| async move {
println!("{:?}", x);
})
.await;
}
Error is:
error: borrowed data cannot be stored outside of its closure
--> src/main.rs:6:36
|
5 | / stream::iter(1..10)
6 | | .scan(0, |s, i| async move {
| |__________________------____________^
| || |
| || ...because it cannot outlive this closure
7 | || *s += i;
8 | || Some(*s)
9 | || })
| ||_________^ cannot be stored outside of its closure
... |
12 | | })
13 | | .await;
| |______________- borrowed data cannot be stored into here...
How can I solve this issue and mutate state inside an async block?