How to return a function that returns a trait in Rust

Viewed 1021

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.

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?

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:

error[E0562] `impl Trait` not allowed outside of function and inherent method return types

What is the best way to solve this issue?

1 Answers

I don't know of any way to do this on stable Rust. However, you can use a type alias for an opaque type (also known as existential type) on Rust nightly like this (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!()
    }
}
Related