我有异步函数,将异步回调传递给它。回调将引用作为参数。
use core::future::Future;
async fn foo(bar: &u32) {}
async fn baz<F, Fut>(f: F)
where
F: FnOnce(&u32) -> Fut,
Fut: Future<Output = ()>,
{
let test: u32 = 42;
f(&test).await;
}
#[tokio::main]
async fn main() {
baz(foo).await;
}如果我试图构建这个(游乐场),我会得到以下错误:
error[E0308]: mismatched types
--> src/main.rs:16:5
|
16 | baz(foo).await;
| ^^^ lifetime mismatch
|
= note: expected associated type `<for<'_> fn(&u32) -> impl Future<Output = ()> {foo} as FnOnce<(&u32,)>>::Output`
found associated type `<for<'_> fn(&u32) -> impl Future<Output = ()> {foo} as FnOnce<(&u32,)>>::Output`
= note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here
--> src/main.rs:7:24
|
7 | F: FnOnce(&u32) -> Fut,
| ^^^据我所知,它对这篇推荐信的一生并不满意。但是,我不明白为什么。
因此,看来借款没有办法比宣布测试的地方更长久。
我遗漏了什么?
发布于 2022-05-12 23:42:55
foo() 有一个隐藏的生命回归的未来。设计的签名就像:
fn foo<'a>(bar: &'a u32) -> impl Future<Output = ()> + 'a {
async move {}
}这样做是为了使函数能够跨bar点保存.await。遗憾的是,它的意思是函数不能满足baz()的界限。错误被混淆,因为生存期是隐藏的,但这正是编译器试图告诉您的:绑定应该类似于where F: for<'a> FnOnce(&'a u32) -> impl Future<Output = ()> + 'a,但在当前的Rust中您不能表达这一点。
有关更多和潜在的解决方案,请参见例如:
发布于 2022-05-13 00:01:01
只是为了解决问题,您可以使用Box而不是引用。
https://stackoverflow.com/questions/72222940
复制相似问题