< 返回版块

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))

}

}

评论区

写评论
Grainspring 2022-05-02 21:16

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的安全。

作者 peacess 2022-04-26 17:03

async_trait的使用self的代码j 可以正常运行的,我想问它这里为什么没有lifetime问题

Grobycn 2022-04-26 08:46

对的,我给出的就是违反生命周期约束的代码

SaltyKitkat 2022-04-25 20:48

--
👇
Grobycn: 假设传入的 i32 的生命周期是 'long, 返回的 Future 生命周期假设是 'short。 生命周期的约束是: 'long: 'short, 且你在 'short 这一段生命周期内不能再借用传入的变量。

据此很容易写出违反生命周期约束的代码

#[tokio::main]
async fn main() {
    let mut x = 1;
    let fut = x.f1();
    x = 2;
    println!("{}", fut.await);
}

这在x=2的地方就会报错吧

BlackLuny 2022-04-25 15:30

f1返回的生命周期小于i32的生命周期,没问题啊

Grobycn 2022-04-25 14:33

假设传入的 i32 的生命周期是 'long, 返回的 Future 生命周期假设是 'short。 生命周期的约束是: 'long: 'short, 且你在 'short 这一段生命周期内不能再借用传入的变量。

据此很容易写出违反生命周期约束的代码

#[tokio::main]
async fn main() {
    let mut x = 1;
    let fut = x.f1();
    x = 2;
    println!("{}", fut.await);
}
1 共 6 条评论, 1 页