我有一个通用异步函数。我希望使用不同的类型来调用它,并并行运行结果的future。但似乎它创建了不同类型的futures(尽管它们都是实现了Future<Output=()>),因此我无法将不同类型的对象放入Vector中,也就不能调用select函数。下面是我的意思:
use std::fmt::Debug;
#[tokio::main]
async fn main() {
// both arguments to test function i32. Works.
let first = Box::pin(test(5));
let second = Box::pin(test(6));
futures::future::select_all(vec![first, second]).await;
}
async fn test<T: Debug>(x: T) {
async {
println!("{:?}", x);
}.await;
}
这种方式不起作用:
use std::fmt::Debug;
#[tokio::main]
async fn main() {
// one argument to test() is i32, the second argument is &str. Doesn't work
let first = Box::pin(test(5));
let second = Box::pin(test("five"));
futures::future::select_all(vec![first, second]).await;
}
async fn test<T: Debug>(x: T) {
async {
println!("{:?}", x);
}.await;
}
在我的具体例子中,我可以使用 select 函数来接受两个 futures,但是如果我有很多 futures,该怎么办?如何选择不同类型的多个 futures?