首页 > 解决方案 > 异步 fn 的类型是什么?

问题描述

我想要一个函数,它需要一个函数指针。 类型应该是什么?async fn
ffn run

async fn foo() {}

fn run(f: /* ??? */) {}

根据异步/等待 RFC

Anasync fn foo(args..) -> T是类型的函数fn(args..) -> impl Future<Output = T>

但是,如果我写

fn run(f: fn() -> impl Future<()>)

我收到错误消息:

`impl Trait` not allowed outside of function and inherent method return types

标签: typesasync-awaitrustfuture

解决方案


您必须在函数签名中引入两个类型参数,一个用于 the Fn,一个用于 the Future,例如

#![feature(futures_api, async_await)]

async fn foo() {}

fn run<G: std::future::Future, F: FnOnce() -> G>(f: F) {
    f();
}

fn main() {
    bar(foo)
}

您可以根据需要FnOnce替换Fn或替换。FnMut


推荐阅读