下面的代码运行正常.
{
let a = &mut 3;
*a = 4;
assert_eq!(*a, 4);
}
以下内容也适用.
{
let a = Some(&3);
let mut b = a.unwrap();
assert_eq!(a.unwrap(), &3);
}
但以下内容无法编译.
{
let a = Some(&mut 3);
assert_eq!(*a.unwrap(), 3);
}
错误是:
40 | let a = Some(&mut 3);
| ^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
41 | assert_eq!(*a.unwrap(), 3);
| - borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
为什么Rust compiler对这些引用的处理方式不同,前两段代码可以使引用的生命周期 比临时的更长,而最后一段则不能?