0
#[derive(Debug)]
struct Earth {
  location: String,
}
#[derive(Debug)]
struct Dinosaur<'a> {
  location: &'a Earth,
  name: String,
}
fn main() {
  let new_york = Earth {
    location: "New York, NY".to_string(),
  };
  let t_rex = Dinosaur {
    location: &new_york,
    name: "T Rex".to_string(),
  };
  println!("{:?}", t_rex);
}

In the above example, you can see a lifetime annotation of 'a. When our struct borrows an instance of Earth, it needs the added lifetime marker. This helps the compiler to know that a Dinosaur should not outlive Earth, which it holds a reference to.

Whenever a struct holds a reference to another struct, isn't it obvious lifetime of struct that holds must be <= lifetime of struct that is hold?

I tried taking off the lifetime annotation and I got an error.

Why can't the compiler simply annotate for me the correct lifetime?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • because language doesn't allow it. – Stargateur May 18 '20 at 22:46
  • tl;dr the duplicate: lifetime annotations let *you* tell *the compiler* what references are supposed to outlive what. The borrow checker basically just "checks your work". e.g. if you write `fn make_dino<'a, 'b>(aleph: &'a Earth, _bet: &'b Earth) -> Dinosaur<'b> { Dinosaur { location: aleph, name: String::new() } }` the borrow checker will notice that you *promised* to return a dinosaur related only to `bet` but you *actually* returned one related to `aleph`, and refuse to compile it. – trent May 18 '20 at 23:35

0 Answers0