简体   繁体   中英

Understanding refs in rust when struct and it's member has different lifetime

I was playing around with the lifetime complexity in rust and I ended up writing the following code:

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};
}

This code compiles, but I am not sure why. As i understand it, the &Human has lifetime of 'b , whereas the reference member i of struct Human has 'c . Why isn't the compiler complaining that 'b can outlive 'c ?

h : Human<'static> , and 'static references meet any output lifetime requirement.

Try writing some code where hi references a variable with shorter lifetime than 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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