我的目标是实现一个返回另一个函数的函数,该函数返回一些特征。更具体地说,返回的函数本身应该返回一个 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 上有什么方法可以做到这一点。但是,您可以为 使用类型别名。不透明型 (也称为存在类型)在 Rust 每晚这样( 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!()
}
}
关于asynchronous - 如何在 Rust 中返回一个返回特征的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60873443/