簡體   English   中英

當struct及其成員具有不同的生存期時,了解rust中的refs

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

我一直在研究銹的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 ,而struct Human的引用成員i的生存期為'c 為什么編譯器不抱怨'b可以超過'c

h : Human<'static>'static引用滿足任何輸出生存期要求。

嘗試編寫一些代碼,其中hi引用壽命短於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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM