gpt4 book ai didi

rust - 编写一个调用另一个异步函数的异步函数

转载 作者:行者123 更新时间:2023-12-04 11:38:59 27 4
gpt4 key购买 nike

我正在尝试创建一个将函数指针作为参数的异步函数。它会做一些事情,调用函数,等待结果,然后再做一些事情:

use std::future::Future;

async fn run_another_async_fn<F, Fut>(f: F)
where
Fut: Future<Output = ()>,
F: FnOnce(&mut i32) -> Fut,
{
let mut i = 42;
println!("running function");
f(&mut i).await;
println!("ran function");
}

async fn foo(i: &mut i32) {}

async fn bar() {
run_another_async_fn(foo);
}
[ view on Rust Playground ]
不幸的是,这无法编译:
error[E0308]: mismatched types
--> src/lib.rs:17:5
|
17 | run_another_async_fn(foo);
| ^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
|
= note: expected associated type `<for<'_> fn(&mut i32) -> impl Future {foo} as FnOnce<(&mut i32,)>>::Output`
found associated type `<for<'_> fn(&mut i32) -> impl Future {foo} as FnOnce<(&mut i32,)>>::Output`
= note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here
--> src/lib.rs:6:28
|
6 | F: FnOnce(&mut i32) -> Fut,
| ^^^
首先,编译器似乎完全找到了它的预期,但它仍然在提示?
其次,什么是“空人生”?我想它一定意味着 '_ ,有什么特别的意义吗?
最后,有什么方法可以编译它?

最佳答案

问题是无法为 F 指定相同的生命周期。和 Futwhere条款。
幸运的是(如果您不介意堆分配 future )有一个简单的解决方法。您可以使用已经存在的 futures::future::BoxFuture;看起来像:

pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
在它的帮助下,您可以为借用和 future 的特征绑定(bind)指定相同的生命周期参数:
 where  for<'a> F: FnOnce(&'a mut i32) -> BoxFuture<'a, ()>,
您还必须添加一个具有正确返回类型的适配器函数 - 即 BoxFuture<'_, T>而不是 impl Future :
fn asd(i: &mut i32) -> BoxFuture<'_, ()> {
foo(i).boxed()
}
或使用闭包:
run_another_async_fn(|i| foo(i).boxed());
因此,您的代码将如下所示:
use futures::future::BoxFuture;
use futures::FutureExt;
use std::future::Future;

async fn run_another_async_fn<F>(f: F)
where
for<'a> F: FnOnce(&'a mut i32) -> BoxFuture<'a, ()>,
{
let mut i = 42;
println!("running function");

f(&mut i).await;

println!("ran function");
}

fn asd(i: &mut i32) -> BoxFuture<'_, ()> {
foo(i).boxed()
}

async fn foo<'a>(i: &'a mut i32) {
// no-op
}

async fn bar() {
run_another_async_fn(asd);
run_another_async_fn(|i| foo(i).boxed());
}

关于rust - 编写一个调用另一个异步函数的异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68882511/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com