rid
rid

Reputation: 63580

Defining an async function type in Rust

If I want to define a type that represents a function, I can write:

type FS = fn(i32) -> i32;

How do I define an async function though?

type FA = async fn(i32) -> i32; // invalid syntax
type FA = fn(i32) -> impl Future<i32>; // unstable and not allowed
type FA<R> = fn(i32) -> R where R impl Future<i32>; // invalid syntax

Also, how would I do this if I wanted to use the Fn / FnMut / FnOnce traits?

Upvotes: 3

Views: 1310

Answers (1)

Aloso
Aloso

Reputation: 5447

The correct syntax is

type FA<R: Future<Output = i32>> = fn(i32) -> R;

However, the compiler warns that bounds on type aliases aren't enforced, so we can omit it:

type FA<R> = fn(i32) -> R;

Then we can use it like this (playground):

fn foo(f: FA<impl Future<Output = i32>>) {
    let _ = f(7);
}

Upvotes: 4

Related Questions