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