fn main() {
struct Foo<'a, T> {
a: &'a mut T,
}
let p1 = 1;
let mut p2 = &p1;
{
let p3 = 2;
let mut p4 = &p3;
let mut f = Foo {
a: &mut p4,
};
f.a = &mut p2;
println!("{}", f.a);
}
println!("{}", p2);
}
当运行此程序时,它遇到错误,如:
error[E0597]: `p3` does not live long enough
--> src/main.rs:10:19
|
10 | let mut p4 = &p3;
| ^^^ borrowed value does not live long enough
...
16 | }
| - `p3` dropped here while still borrowed
17 | println!("{}", p2);
| -- borrow later used here
-- borrow later used here
这是我的第一个问题:为什么会存在这些错误?
如果我注释最后一行,例如:
fn main() {
struct Foo<'a, T> {
a: &'a mut T,
}
let p1 = 1;
let mut p2 = &p1;
{
let p3 = 2;
let mut p4 = &p3;
let mut f = Foo {
a: &mut p4,
};
f.a = &mut p2;
println!("{}", f.a);
}
// println!("{}", p2);
}
它运行成功.通过参考rustonomicon,
f.a = &mut p2;
&;‘a mut T在’a上是协变的,在T上是不变的,它应该不会成功编译.但是成功了,为什么?
如果我注释最后一行,它应该编译不成功.