首先,我知道有很多类似的问题,我也读了很多讨论,但我仍然不明白我的情况是怎么回事.
struct Test {
x: u32,
}
fn main() {
let mut t = & mut Test { x: 0 };
println!("{}", t.x);
t = & mut Test { x: 1 };
println!("{}", t.x);
}
好的,这会如预期的那样给出一个错误:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:8:15
|
8 | t = & mut Test { x: 1 };
| ^^^^^^^^^^^^^- temporary value is freed at the end of this statement
| |
| creates a temporary value which is freed while still in use
"creates a temporary value which is freed while still in use"--没错,但是why doesn't this error happen before呢?只有在第二次赋值&mut
时才会发生这种情况,而第一次就可以了.难道它不应该也创造一个被丢弃的临时价值吗?这就是我不能理解的.
此外,如果我删除mut
,那么一切都会正常运行:
fn main() {
let mut t = & Test { x: 0 };
println!("{}", t.x);
t = & Test { x: 1 };
println!("{}", t.x);
}
但是为什么呢?不可变引用仍然是引用,它仍然指向一些数据,并且临时值仍然被删除.因此,引用应该是无效的.也应该给出错误,但不,它没有.为什么?
但等等,还有更多!如果我对Test
实现Drop
个特征:
impl Drop for Test {
fn drop(& mut self) {
}
}
现在我又得到了同样的错误,没有更改main()
的代码.这有什么关系呢?