[英]How to return a function that returns a trait in Rust
我的目标是实现一个返回另一个函数的函数,该函数返回一些特征。 更具体地说,返回的函数本身应该返回一个 Future。
要返回一个返回具体类型的函数,我们显然可以这样做:
fn returns_closure() -> impl Fn(i32) -> i32 {
|x| x + 1
}
但是如果我们想要返回一个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 每晚使用不透明类型(也称为存在类型)的类型别名:
#![feature(type_alias_impl_trait)]
use futures::Future;
type Fut<O> = impl Future<Output = O>;
fn factory<O>() -> impl Fn() -> Fut<O> {
|| async {
todo!()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.