Scope of addresses: Does not live long enough

淺唱寂寞╮ 提交于 2020-01-04 21:34:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!