我想从 Rust 中的函数返回一个异步闭包。
稍后接受闭包作为参数的函数 (
for_each_concurrent
) 期望类似于 FnMut() -> dyn Future<Output = ()>
的东西(但有一些参数,这应该不重要)。
我尝试创建一个返回特征对象的函数如《Rust Book》中所述。 但这会给我带来错误
expected trait object 'dyn Future', found 'async' block
和其他错误。我不知道如何正确执行此操作。
这是一个最小的例子:
use std::future::Future;
#[tokio::main]
async fn main() {
let async_function = foo();
async_function().await;
}
fn foo() -> Box<dyn FnMut() -> dyn Future<Output = ()>> {
Box::new(|| async {
// do async stuff
print!("Hello, World!");
})
}
虽然这有效:
use std::future::Future;
#[tokio::main]
async fn main() {
let async_function = || async {
// do async stuff
print!("Hello, World!");
};
async_function().await;
}
我尝试将返回类型指定为 async_block,但这也是不可能的。 我还尝试使用
impl
安装 Box<dyn ...>
来指定返回类型。
在撰写答案时,在 Rust 中从函数返回异步闭包是不可能。
完美的“解决方案”:
use std::future::Future;
fn ret_async_closure() -> impl FnOnce() -> impl Future<Output=()> {
move || {
async {
/* do something*/
}
}
}
你会得到一个编译错误:
error[E0562]: `impl Trait` is not allowed in the return type of `Fn` trait bounds
--> src/main.rs:3:44
|
3 | fn ret_async_closure() -> impl FnOnce() -> impl Future<Output=()> {
| ^^^^^^^^^^^^^^^^^^^^^^
|
= note: `impl Trait` is only allowed in arguments and return types of functions and methods
= note: see issue #99697 <https://github.com/rust-lang/rust/issues/99697> for more information
您可以注意到它提到了该功能的跟踪问题:https://github.com/rust-lang/rust/issues/99697。
但是,作为解决方法,您可以...盒子未来
use std::future::Future;
fn ret_async_closure() -> impl FnOnce() -> Box<dyn Future<Output=()>> {
move || {
Box::new(async {
/* do something*/
})
}
}
此解决方案可能会带来性能损失。使用类似函数的声明性宏
macro_rules! ret_async_closure {
() => {
move || {
async {
/* do something*/
}
}
};
}