繁体   English   中英

生命周期问题:“类型具有不同的生命周期,但是来自“自身”的数据会流入……”

[英]Lifetime Problem: “types have different lifetimes, but data from 'self' flows into…”

我有以下代码:

#[derive(Clone, Copy)]
pub struct HitRecord<'a> {
    pub t: f32,
    pub p: Vector3<f32>,
    pub normal: Vector3<f32>,
    pub material: Option<&'a Material>,
}

pub struct Sphere<T>
where
    T: Material,
{
    pub center: Vector3<f32>,
    pub radius: f32,
    pub material: T,
}

impl<T> Sphere<T> {
    fn hit<'a, 'b>(&'a self, ray: &Ray, t_min: f32, t_max: f32, record: &'b mut HitRecord) -> bool
    where
        'a: 'b,
    {
        record.material = Some(&self.material);
    }
}

我知道record生存期必须短于self ,因此我为它们分配了不同的生存期,并将'a设置为'b 但是我仍然得到这个:

error[E0623]: lifetime mismatch
  --> src\tracer\sphere.rs:54:35
   |
30 |     fn hit<'a, 'b>(&'a self, ray:&Ray, t_min:f32, t_max:f32, record:&'b mut HitRecord) -> bool where 'a: 'b {
   |                    --------                                                 ---------
   |                    |
   |                    these two types are declared with different lifetimes...
...
54 |                 record.material = Some(&self.material);
   |                                   ^^^^^^^^^^^^^^^^^^^^ ...but data from `self` flows into `record` here

我相信现在已经解决了这个一生的问题了好几个小时,我不知道这里发生了什么。 我究竟做错了什么?

HitRecord中的引用的生存期必须设置为与&self的生存期相同(或更短),以便从record到self的引用正确。 您甚至不必显式地在'a和'b之间建立关系,因为重要的不是record本身的生存期,而是struct成员material的生存期。 该签名应该起作用:

fn hit<'a>(&'a self, ray:&Ray, t_min:f32, t_max:f32, record:&mut HitRecord<'a>) -> bool

编辑 :我已经看到您可能不知道的一件事是您正在创建特征对象,即启用动态调度的东西。 如果不需要,可能需要将HitRecord的声明HitRecord

#[derive(Clone, Copy)]
pub struct HitRecord<'a, T: Material> {
    pub t: f32,
    pub p: Vector3<f32>,
    pub normal: Vector3<f32>,
    pub material: Option<&'a T>
}

这样,您将结构固定为实现Material的某个静态已知类型,该实现了静态的编译时间分配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM