我正在玩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
?
答案 0 :(得分: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