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?
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.