types - 异步 fn 的类型是什么?
问题描述
我想要一个函数,它需要一个函数指针。
类型应该是什么?async fn
f
fn run
async fn foo() {}
fn run(f: /* ??? */) {}
根据异步/等待 RFC:
An
async fn foo(args..) -> T
是类型的函数fn(args..) -> impl Future<Output = T>
。
但是,如果我写
fn run(f: fn() -> impl Future<()>)
我收到错误消息:
`impl Trait` not allowed outside of function and inherent method return types
解决方案
您必须在函数签名中引入两个类型参数,一个用于 the Fn
,一个用于 the Future
,例如
#![feature(futures_api, async_await)]
async fn foo() {}
fn run<G: std::future::Future, F: FnOnce() -> G>(f: F) {
f();
}
fn main() {
bar(foo)
}
您可以根据需要FnOnce
替换Fn
或替换。FnMut
推荐阅读
- javascript - 为什么在 React 中使用 .map() 时需要扩展运算符,但在纯 JavaScript 中不需要?
- ios - 在 SwiftUI 中运行时创建控件
- powershell - msExchDelegateListBL 属性 - 无法修改该属性,因为它归系统所有
- r - `prcomp` 用于什么类型的数据?
- node.js - 如何在一定时间后触发 throw 指令?
- python - 类属性
- webassembly - 是否可以使用 emscripten 为 webassembly 编译 x264?
- jdbc - 如何使用 jdbc 将远程文件加载到 db2 数据库中
- jquery - 我如何使用 jquery 验证选择选项?
- angular - 使用永久令牌的 Facebook Graph API 主题标签搜索