< 返回版块
peacess
发表于 2022-04-25 11:13
Tags:async trait lifetime
在 async_trait的实现中,如下:
impl AsyncTrait for i32 {
fn f1(&mut self) -> Pin<Box<dyn Future<Output = i32> + Send + '_>> {
async fn run(_self: &mut i32) -> i32 {
*_self
}
Box::pin(run(self))
}
}
评论区
写评论fn f1(&mut self) -> Pin<Box<dyn Future<Output = i32> + Send + '_>>
函数签名经过编译器处理后相当于 fn f1(&'a mut self) -> Pin<Box<dyn Future<Output = i32> + Send + 'a>>
这样约束dyn Future<Output = i32> + Send + 'a只在'a能有效,以致保证了lifetime的安全。
async_trait的使用self的代码j 可以正常运行的,我想问它这里为什么没有lifetime问题
对的,我给出的就是违反生命周期约束的代码
--
👇
Grobycn: 假设传入的
i32
的生命周期是'long
, 返回的Future
生命周期假设是'short
。 生命周期的约束是:'long: 'short
, 且你在'short
这一段生命周期内不能再借用传入的变量。据此很容易写出违反生命周期约束的代码
这在x=2的地方就会报错吧
f1返回的生命周期小于i32的生命周期,没问题啊
假设传入的
i32
的生命周期是'long
, 返回的Future
生命周期假设是'short
。 生命周期的约束是:'long: 'short
, 且你在'short
这一段生命周期内不能再借用传入的变量。据此很容易写出违反生命周期约束的代码