【问题标题】:How to return a function that returns a trait in Rust如何返回一个返回 Rust 特征的函数
【发布时间】:2020-07-07 10:49:27
【问题描述】:

我的目标是实现一个返回另一个函数的函数,该函数返回一些特征。更具体地说,返回的函数本身应该返回一个 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

解决此问题的最佳方法是什么?

【问题讨论】:

  • @Stargateur 这不是返回闭包的未来而不是返回未来的闭包吗?
  • @SvenMarnach 直到异步关闭稳定...

标签: asynchronous rust closures traits


【解决方案1】:

我不知道有什么方法可以在稳定的 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!()
    }
}

【讨论】:

  • 似乎在稳定的 Rust 中还没有一个好的方法可以做到这一点,不像我错过了什么。
猜你喜欢
  • 1970-01-01
  • 2020-12-31
  • 2022-07-31
  • 1970-01-01
  • 2018-01-01
  • 2019-08-04
  • 1970-01-01
  • 2017-05-12
相关资源
最近更新 更多