我对这两个看似相似的程序的结果感到惊讶。
fn main() {
let y: &int = &31i;
println!("My number is {}.",*y)
}
//Output
My number is 31.
但是,这段代码给了我一个错误。
fn main() {
let y: ∫
y = &31i;
println!("My number is {}.",*y)
}
// Output on Rust Playpen
3:12 error: borrowed value does not live long enough
5:2 note: reference must be valid for the block at 1:10...
3:13 note: ...but borrowed value is only valid for the statement at 3:4
显然,如果在声明 y
后将其分配给 y
,则 &31i
就会超出范围。但是,如果它位于声明 y
的同一行,则它会保留在范围内。我不明白这是为什么。
Rust 的设计是如何让它表现出这种行为的?提前致谢。
最佳答案
我认为发生这种情况是因为 &
运算符在绑定(bind)或其他地方使用时的规则不同。
这个:
let y: &int = &31i;
相当于:
let temp: int = 31i;
let y: &int = &temp;
除了 temp
是不可见的。这是解释的,例如在 lifetimes guide ,尽管本指南似乎是尚未重写的旧版本(与其他指南一样)。
但是这个:
let y: ∫
y = &31i;
由于某种原因没有这样的语义,因此31i
仅存在于其表达式中(即31i
)。因此,您无法引用它,因为它会立即被丢弃。
我认为这有点违反直觉,可能值得提出一个问题。也许这只是因为更重要的事情而被忽视的事情之一。
关于rust - 地址范围: Does not live long enough,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049194/