rust - 如何选择或加入不同类型的 future ?

标签 rust

我有一个通用的异步函数。我想用不同的类型调用它并并行运行结果 future 。但它似乎创建了不同类型的 future (尽管它们都是 impl Future),因此我不能将不同类型的对象放入 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;
}

在我的具体示例中,我可以使用接受两个 future 的 select,但是如果我有很多 future 怎么办?如何选择多个不同类型的 future ?

最佳答案

你只需要稍微帮助编译器检测正确的类型。我们使用 dynamic dispatching在此处使用 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;
}

所以我所做的就是将 Vector 提取到一个变量中并为其指定一个显式类型。

关于rust - 如何选择或加入不同类型的 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64331787/

相关文章:

rust - 在近协议(protocol)合约的函数中返回多个值

rust - 如何从 HashMap 获取可变结构?

plugins - 如何找出 rustc::middle::ty::Ty 代表什么类型?

rust - 将宏匹配器插入字符串文字中

rust - 为什么不可变字符串可以调用 String::add(mut self, other: &str)

segmentation-fault - 为什么这个 Rust 程序不会崩溃?

rust - 无法使用 MIO 编译项目 - 使用不稳定的库功能 'udp_extras'

rust - 范围文字和范围模式之间有什么区别(例如 `...` 和 `..=` 之间)?

generics - 无法访问动态特征实现中的结构字段

rust - 关于期望类型的奇怪错误