Hi, I had a lifetime error when referencing data inside a async closure like below.
Please help. Thanks a lot.
use futures::future;
use futures::stream::{self, StreamExt};
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let stream = stream::iter(1..=3);
let stream2 = stream::iter(1..=3);
let data = Data::new();
future::join(
stream.for_each(|_| inc1(&mut data)),
stream2.collect::<Vec<_>>(),
);
Ok(())
}
async fn inc1(data: &mut Data) -> () {
data.n += 1;
future::ready(()).await
}
struct Data {
n: u32,
}
impl Data {
fn new() -> Data {
Data { n: 0 }
}
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/main.rs:13:34
|
13 | stream.for_each(|_| inc1(&mut data)),
| ^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'_` as defined on the body at 13:25...
--> src/main.rs:13:25
|
13 | stream.for_each(|_| inc1(&mut data)),
| ^^^^^^^^^^^^^^^^^^^
note: ...so that closure can access `data`
--> src/main.rs:13:34
|
13 | stream.for_each(|_| inc1(&mut data)),
| ^^^^^^^^^
note: but, the lifetime must be valid for the call at 12:5...
--> src/main.rs:12:5
|
12 | / future::join(
13 | | stream.for_each(|_| inc1(&mut data)),
14 | | stream2.collect::<Vec<_>>(),
15 | | );
| |_____^
note: ...so type `futures_util::future::join::Join<futures_util::stream::stream::for_each::ForEach<futures_util::stream::iter::Iter<std::ops::RangeInclusive<i32>>, impl core::future::future::Future, [closure@src/main.rs:13:25: 13:44 data:&mut Data]>, futures_util::stream::stream::collect::Collect<futures_util::stream::iter::Iter<std::ops::RangeInclusive<i32>>, std::vec::Vec<i32>>>` of expression is valid during the expression
--> src/main.rs:12:5
|
12 | / future::join(
13 | | stream.for_each(|_| inc1(&mut data)),
14 | | stream2.collect::<Vec<_>>(),
15 | | );
| |_____^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0495`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.