如何在 Rust 中竞速一系列 Futures?

How to race a collection of Futures in Rust?

给定 Futures 的集合,比如 Vec<impl Future<..>>,我如何同时阻止和 运行 所有 Futures 直到第一个 Future准备好了吗?

我能找到的最接近的特征是 select macro (which is also available in Tokio)。不幸的是,它只适用于明确数量的 Future,而不是处理它们的集合。

Javascript 中有一个与此功能等效的项,称为 Promise.race。有没有办法在 Rust 中做到这一点?

或者也许有一种方法可以使用另一种模式(可能是通道)来实现这个用例?

我找到了使用 select_all function from the futures 库的解决方案。

这里有一个简单的例子来演示如何使用它来赛跑一组期货:

use futures::future::select_all;
use futures::FutureExt;
use tokio::time::{delay_for, Duration};

async fn get_async_task(task_id: &str, seconds: u64) -> &'_ str {
    println!("starting {}", task_id);
    let duration = Duration::new(seconds, 0);

    delay_for(duration).await;

    println!("{} complete!", task_id);
    task_id
}

#[tokio::main]
async fn main() {
    let futures = vec![

        // `select_all` expects the Futures iterable to implement UnPin, so we use `boxed` here to
        // allocate on the heap:
        // https://users.rust-lang.org/t/the-trait-unpin-is-not-implemented-for-genfuture-error-when-using-join-all/23612/3
        // https://docs.rs/futures/0.3.5/futures/future/trait.FutureExt.html#method.boxed

        get_async_task("task 1", 5).boxed(),
        get_async_task("task 2", 4).boxed(),
        get_async_task("task 3", 1).boxed(),
        get_async_task("task 4", 2).boxed(),
        get_async_task("task 5", 3).boxed(),
    ];

    let (item_resolved, ready_future_index, _remaining_futures) =
        select_all(futures).await;

    assert_eq!("task 3", item_resolved);
    assert_eq!(2, ready_future_index);
}

下面是上面代码的 link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f32b2ed404624c1b0abe284914f8658d

感谢@Herohtar 在上面的评论中提出建议 select_all