如何解决异步闭包返回类型的生命周期
考虑以下代码:
async fn f(x: &i32) -> i32 {
todo!()
}
fn g<F,Fut>(f: F)
where
F: Send + Sync + 'static,for<'a> F: Fn(&'a i32) -> Fut,Fut: Future<Output = i32> + Send + Sync,{
todo!()
}
fn main() {
g(f);
}
编译器抱怨
error[E0308]: mismatched types
--> src/main.rs:17:5
|
17 | g(f);
| ^ lifetime mismatch
|
= note: expected associated type `<for<'_> fn(&i32) -> impl Future {f} as FnOnce<(&i32,)>>::Output`
found associated type `<for<'_> fn(&i32) -> impl Future {f} as FnOnce<(&'a i32,)>>::Output`
= note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here
--> src/main.rs:10:31
|
10 | for<'a> F: Fn(&'a i32) -> Fut,| ^^^
我认为问题在于异步函数中返回值的生命周期与 x
的生命周期相关,但我不确定如何在 where
子句中表达这一点g
?
解决方法
我认为您正在寻找这个:
use core::future::Future;
async fn f(x: &i32) -> i32 {
todo!()
}
fn g<'a,F,Fut>(f: F)
where
F: Send + Sync + 'static,F: Fn(&'a i32) -> Fut,Fut: Future<Output = i32> + Send + Sync,{
todo!()
}
fn main() {
g(f);
}
将 x 的生命周期绑定到 g 的生命周期(不确定这是否是您想要的......我不知道在 where 子句中如何做到这一点)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。