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

问题描述 投票:0回答:1

我正在玩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更活跃?

reference rust lifetime ownership borrow-checker
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.