如何返回一个返回 Rust 特征的函数

Fab*_*ger 5 closures asynchronous traits rust

我的目标是实现一个返回另一个函数的函数,该函数返回一些特征。更具体地说,返回的函数本身应该返回一个 Future。

要返回一个返回具体类型的函数,我们显然可以这样做:

fn returns_closure() -> impl Fn(i32) -> i32 {
    |x| x + 1
}
Run Code Online (Sandbox Code Playgroud)

但是如果i32我们想返回 a呢Future

我尝试了以下方法:

use futures::Future;

fn factory() -> (impl Fn() -> impl Future) {
    || async {
        // some async code
    }
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为impl不允许使用第二个关键字:

error[E0562] `impl Trait` not allowed outside of function and inherent method return types

解决这个问题的最佳方法是什么?

Alo*_*oso 4

我不知道有什么方法可以在稳定的 Rust 上做到这一点。但是,您可以在 Rust nightly 上使用不透明类型(也称为存在类型)的类型别名,如下所示( playground):

#![feature(type_alias_impl_trait)]

use futures::Future;

type Fut<O> = impl Future<Output = O>;

fn factory<O>() -> impl Fn() -> Fut<O> {
    || async {
        todo!()
    }
}
Run Code Online (Sandbox Code Playgroud)