如果要定义代表函数的类型,可以编写:
type FS = fn(i32) -> i32;
我如何定义异步函数呢?
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
另外,如果我想使用
Fn
/FnMut
/FnOnce
特性,该怎么办?
最佳答案
正确的语法是
type FA<R: Future<Output = i32>> = fn(i32) -> R;
但是,编译器警告说,类型别名的边界未强制执行,因此我们可以忽略它:
type FA<R> = fn(i32) -> R;
然后我们可以像这样(playground)使用它:
fn foo(f: FA<impl Future<Output = i32>>) {
let _ = f(7);
}
关于types - 在Rust中定义一个异步函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60351262/