我的目标是实现一个返回另一个函数的函数,该函数返回一些特征。更具体地说,返回的函数本身应返回Future。
要返回一个返回具体类型的函数,我们显然可以这样做:
fn returns_closure() -> impl Fn(i32) -> i32 {
|x| x + 1
}
但是如果要返回i32
而不是Future
,该怎么办?
我尝试了以下操作:
use futures::Future;
fn factory() -> (impl Fn() -> impl Future) {
|| async {
// some async code
}
}
这不起作用,因为不允许第二个impl
关键字:
error[E0562] `impl Trait` not allowed outside of function and inherent method return types
解决此问题的最佳方法是什么?
我不知道要在稳定的Rust上执行此操作的任何方法。但是,您可以像这样(playground):在Rust每晚对opaque type
(也称为存在类型)使用类型别名。#![feature(type_alias_impl_trait)]
use futures::Future;
type Fut<O> = impl Future<Output = O>;
fn factory<O>() -> impl Fn() -> Fut<O> {
|| async {
todo!()
}
}