当struct和它的成员具有不同的生命周期时,理解锈中的引用

时间:2017-12-29 20:42:10

标签: reference rust lifetime ownership borrow-checker

我正在玩lifetime生锈的复杂性,我最后编写了以下代码:

trait Boss<'a, 'c> {
  fn work(&self, &'a i32) -> &'c i32;
}

struct Human<'c> {
  i:&'c i32 
}

impl<'a, 'b, 'c> Boss<'a, 'c>  for &'b Human <'c> {
  fn work(&self, v:&'a i32) -> &'c i32 {
    &self.i
  }
}


fn main () {
  let h = Human {i:&1};
}

此代码编译,但我不确定原因。据我了解,&Human的有效期为'b,而i的参考成员struct Human'c。为什么编译器抱怨'b可以超过'c

1 个答案:

答案 0 :(得分:0)

h : Human<'static>'static引用符合任何输出生存期要求。

尝试编写一些代码,其中h.i引用一个寿命比h短的变量。

fn main () {
    let mut h = Human {i:&1};
    {
        let x : i32 = 3;
        h.i = &x;
    }
    let r = (&h).work(&3);
}

error[E0597]: `x` does not live long enough
  --> a.rs:21:5
   |
20 |         h.i = &x;
   |                - borrow occurs here
21 |     }
   |     ^ `x` dropped here while still borrowed
22 |     let r = (&h).work(&3);
23 | }
   | - borrowed value needs to live until here