2
我对这两个看似相似的程序的结果感到惊讶。地址范围:不够长
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
显然,&31i
超出范围,如果它y
已经被宣布后已分配给y
。但是,如果它位于声明y
的同一行上,则它保持在范围内。我不明白这是为什么。
Rust的设计如何让它表现如此呢?提前致谢。
我记得在Niko的博客上看过一篇文章,他试图找出临时应用的生命周期。看起来很难提出一个既宽松又有限的详细规则(因为你希望借款的范围很紧张......)。 – 2014-11-21 08:57:52