如何选择或加入不同类型的期货?

4

我有一个通用异步函数。我希望使用不同的类型来调用它,并并行运行结果的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?

1个回答

2
你只需要帮助编译器一点,让它能够检测到正确的类型。我们在这里使用动态分派dyn关键字。
use std::fmt::Debug;
use std::pin::Pin;

#[tokio::main]
async fn main() {
    // one argument to test() is i32, the second argument is &str.
    let first = Box::pin(test(5));
    let second = Box::pin(test("five"));
    let v: Vec<Pin<Box<dyn futures::Future<Output = ()>>>> = vec![first, second];
    futures::future::select_all(v).await;
}

async fn test<T: Debug>(x: T) {
    async {
        println!("{:?}", x);
    }
    .await;
}

所以我所做的就是将向量提取到一个变量中,并明确其类型。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接