What type should I use for a vector that stores futures?
I tried to make multiple concurrent requests on the same URL and save all the futures into the vector to use with join_all
.
If I don't set a type for the vector explicitly, everything works. I understand that Rust can find the proper type of a variable. CLion determines the vector type as Vec<dyn Future<Output = ()>>
, but when I try to set the type by myself, it gives me an error:
error[E0277]: the size for values of type `dyn core::future::future::Future<Output = ()>` cannot be known at compilation time
--> src/lib.rs:15:23
|
15 | let mut requests: Vec<dyn Future<Output = ()>> = Vec::new();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn core::future::future::Future<Output = ()>`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
= note: required by `std::vec::Vec`
I must declare the type as Vec<Pin<Box<dyn Future<Output=()>>>>
which forces me to wrap result of function into requests.push(Pin::from(Box::new(request(i))));
use futures::future::join_all;
use std::future::Future;
use std::pin::Pin;
async fn request(n: i32) {
println!("Started: {}", n);
let response = reqwest::get("https://www.rust-lang.org")
.unwrap()
.text()
.unwrap();
println!("Completed: {}. Response: {}", n, &response[0..10]);
}
async fn main() {
let mut requests: Vec<dyn Future<Output = ()>> = Vec::new();
for i in 0..5 {
requests.push(request(i));
}
join_all(requests).await;
}
Which type it should be?
Vec<dyn Future<Output=()>>
is not a valid type since it's size unknown at compile time. It is a type hint to represent Opaque type which returns fromasync fn request(n: i32) {}
. It might be a better choice if it displays like thatVec<impl Future<Output=()>>
, but still this is not a valid type. Consider this type asT
which implementsFuture<Output=()>
. Also you don't need to Pin Box your Futures unless your opaque types are different : please see – Pluralizelet mut requests:Vec<_> = Vec::new();
– Pluralize