[英]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.