问题
I was surprised by the result of these two apparently similar programs.
fn main() {
let y: &int = &31i;
println!("My number is {}.",*y)
}
//Output
My number is 31.
However, this code gives me an error.
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
Apparently, &31i goes out of scope if it's assigned to y after y has been declared. However, if it is on the same line where y is declared it stays in scope. I don't see the reason why this is.
What about Rust's design makes it behave this way? Thanks in advance.
回答1:
I think this happens because of different rules for & operator when it is used in bindings or elsewhere.
This:
let y: &int = &31i;
is equivalent to this:
let temp: int = 31i;
let y: &int = &temp;
except that temp is invisible. This is explained e.g. in lifetimes guide, though this guide seems to be the older version which has not been rewritten yet (like other guides).
But this:
let y: ∫
y = &31i;
does not have such semantics for some reason, so 31i lives only inside its expression (i.e. 31i). Consequently, you can't take a reference to it because it is discarded immediately.
I'd argue that this is somewhat counterintuitive and probably worth creating an issue. Maybe it is just one of those things which were overlooked because of more important things.
来源:https://stackoverflow.com/questions/27049194/scope-of-addresses-does-not-live-long-enough