如何将 Future 作为函数参数传递?

How to pass a Future as a function argument?

我习惯了 Scala 的 Future 类型,在这种类型中,您可以将要返回的任何对象包装在 Future[..] 中以指定它。

我的 Rust 函数 hello returns Query 我似乎无法将该结果作为类型为 Future<Output = Query> 的参数传递。为什么不,我应该如何更好地输入它?

当我尝试将 future 作为参数传递时失败:

use std::future::Future;

struct Person;
struct DatabaseError;

type Query = Result<Vec<Person>, DatabaseError>;

async fn hello_future(future: &dyn Future<Output = Query>) -> bool {
    future.await.is_ok()
}

async fn hello() -> Query {
    unimplemented!()
}

async fn example() {
    let f = hello();
    hello_future(&f);
}

fn main() {}

编译失败并出现错误:

error[E0277]: `&dyn Future<Output = Result<Vec<Person>, DatabaseError>>` is not a future
 --> src/main.rs:9:5
  |
9 |     future.await.is_ok()
  |     ^^^^^^^^^^^^ `&dyn Future<Output = Result<Vec<Person>, DatabaseError>>` is not a future
  |
  = help: the trait `Future` is not implemented for `&dyn Future<Output = Result<Vec<Person>, DatabaseError>>`
  = note: required by `poll`

async 函数脱糖以返回实现 Future 特征的不透明值。这意味着您可以接受实现该特征的泛型类型。最简洁的语法是 impl Trait,但您也可以引入命名泛型参数:

async fn hello_future(future: impl Future<Output = Query>) -> bool {
    future.await.is_ok()
}

async fn example() {
    let f = hello();
    hello_future(f);
}

另请参阅: