I'm curious as to why this results in the "async block may outlive the current function".
It seems to me that the "await" call on the Vec<_> collected from the FuturesOrdered ensures any futures constructed by the map wont outlive the function?
(I'm not so concerned about adding "move" to solve this, its inconvenient as I will need to clone some other data that will need to make into the async block but not a show stopper)
use futures::StreamExt;
#[derive(Debug)]
struct Data{
val: usize,
name: String
}
struct DataGroup{
names: Vec<Data>
}
impl DataGroup{
async fn return_future(self) -> Vec<usize>{
self.names.iter().map(|n| async {
println!(" {:?}", n);
0
}).collect::<futures::stream::FuturesOrdered<_>>().collect::<Vec<_>>().await
}
}
fn main() {
let mut dg = DataGroup{names: vec![]};
for i in 0..10{
dg.names.push(Data{val: i, name:format!("elem {i}")});
}
let _vals = futures::executor::block_on ( dg.return_future());
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0373]: async block may outlive the current function, but it borrows `n`, which is owned by the current function
--> src/main.rs:16:35
|
16 | self.names.iter().map(|n| async {
| ___________________________________^
17 | | println!(" {:?}", n);
| | - `n` is borrowed here
18 | | 0
19 | | }).collect::<futures::stream::FuturesOrdered<_>>().collect::<Vec<_>>().await
| |_________^ may outlive borrowed value `n`
|
note: async block is returned here
--> src/main.rs:16:35
|
16 | self.names.iter().map(|n| async {
| ___________________________________^
17 | | println!(" {:?}", n);
18 | | 0
19 | | }).collect::<futures::stream::FuturesOrdered<_>>().collect::<Vec<_>>().await
| |_________^
help: to force the async block to take ownership of `n` (and any other referenced variables), use the `move` keyword
|
16 | self.names.iter().map(|n| async move {
| ++++
For more information about this error, try `rustc --explain E0373`.
error: could not compile `playground` due to previous error