Address volume: does not live long enough

I was surprised at the result of these two seemingly similar programs.

fn main() {
    let y: &int = &31i;
    println!("My number is {}.",*y)
}
//Output
My number is 31.

      

However, this code is giving 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

out of scope if declared y

after y

. However, if it is on the same line as it is declared y

, it remains in scope. I see no reason why this is so.

How about Rust's design, does it behave like this? Thank you in advance.

+2


source to share


1 answer


I think this is due to different rules for the operator &

when used in bindings or elsewhere.

It:

let y: &int = &31i;

      

is equivalent to this:

let temp: int = 31i;
let y: &int = &temp;

      



except that it is temp

invisible. This is explained, for example, in the guide to life , although this guide seems to be an older version that has not yet been rewritten (like the other guides).

But this:

let y: ∫
y = &31i;

      

for some reason, it does not have such semantics, therefore it 31i

lives only inside its expression (i.e. 31i

). Hence, you cannot reference it because it is discarded immediately.

I would say this is somewhat controversial and probably worth creating a problem. Perhaps this is just one of those things that have been overlooked due to more important things.

+3


source







All Articles