[英]How to return a function that returns a trait in Rust
My goal is to implement a function that returns another function, which returns some trait.我的目标是实现一个返回另一个函数的函数,该函数返回一些特征。 To be more specific, the returned function should itself return a Future.更具体地说,返回的函数本身应该返回一个 Future。
To return a function that returns a concrete type, we obviously can do this:要返回一个返回具体类型的函数,我们显然可以这样做:
fn returns_closure() -> impl Fn(i32) -> i32 {
|x| x + 1
}
But what if instead of i32
we want to return a Future
?但是如果我们想要返回一个Future
而不是i32
呢?
I tried the following:我尝试了以下方法:
use futures::Future;
fn factory() -> (impl Fn() -> impl Future) {
|| async {
// some async code
}
}
This does not work because the second impl
keyword is not allowed:这不起作用,因为不允许使用第二个impl
关键字:
error[E0562] `impl Trait` not allowed outside of function and inherent method return types
What is the best way to solve this issue?解决此问题的最佳方法是什么?
I don't know of any way to do this on stable Rust.我不知道在稳定的 Rust 上有什么方法可以做到这一点。 However, you can use a type alias for an opaque type (also known as existential type) on Rust nightly like this ( playground ):但是,您可以像这样( 操场)在 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.