如何 return 一个 return 是 Rust 特征的函数
How to return a function that returns a trait in Rust
我的目标是实现一个函数,该函数 return 是另一个函数,return 具有某些特征。更具体地说,returned 函数本身应该 return 一个 Future.
对于return一个return具体类型的函数,我们显然可以这样做:
fn returns_closure() -> impl Fn(i32) -> i32 {
|x| x + 1
}
但是,如果我们想要 return 一个 Future
而不是 i32
怎么办?
我尝试了以下方法:
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 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!()
}
}
我的目标是实现一个函数,该函数 return 是另一个函数,return 具有某些特征。更具体地说,returned 函数本身应该 return 一个 Future.
对于return一个return具体类型的函数,我们显然可以这样做:
fn returns_closure() -> impl Fn(i32) -> i32 {
|x| x + 1
}
但是,如果我们想要 return 一个 Future
而不是 i32
怎么办?
我尝试了以下方法:
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 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!()
}
}