Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

p143, 所举的三个例子都是有问题的 (+ p147) #44

Open
slanterns opened this issue Jan 14, 2020 · 3 comments
Open

p143, 所举的三个例子都是有问题的 (+ p147) #44

slanterns opened this issue Jan 14, 2020 · 3 comments

Comments

@slanterns
Copy link

slanterns commented Jan 14, 2020

fn main() {
    let mut i = 0;
    let p1 = &mut i;
    *p1 = 1;
    let x = i;
}
fn main() {
    let mut i = 0;
    let p1 = &mut i;
    i = 1;
}
fn main() {
    let mut i = 0;
    let p1 = &mut i;
    let p2 = &mut i;
}

这三个例子都可以正常编译通过。原因在于在前两个例子里读/写 i 前、第三个例子里通过 p2 借用 i 前,p1 的生命周期都已经结束了,不会干扰后续的操作。

解决:在每个例子最后简单加个 p1;, 让 p1 多存活一会儿就可以引发报错了(另外 E0503 E0506 E0499 这三个错误的描述在最新的 rustc 里都已经经过一定修改了)

@slanterns slanterns changed the title p143, 所举的三个例子都是有问题的 p143, 所举的三个例子都是有问题的 (+ p147) Jan 14, 2020
@slanterns
Copy link
Author

以及 p147:

fn main() {
    let mut arr = vec![1i32; 5];
    let p = &arr[0];
    for i in 1..100 {
        arr.push(i);
    }
}

也可以正常通过编译,因为 p 的生命周期没有持续到后面。
改成:

fn main() {
    let mut arr = vec![1i32; 5];
    let p = &arr[0];
    for i in 1..100 {
        arr.push(i);
    }
    p;
}

就好了。

@slanterns
Copy link
Author

slanterns commented Jan 14, 2020

话说这应该是 NLL 解决了的问题?但是放着当例子还是不合适了,会让人非常迷惑。

@F001
Copy link
Owner

F001 commented Jan 15, 2020

你说的有道理。当时写的时候 NLL 还在 RFC 里面,没有合适的工具做测试。这些例子在 NLL 启用后都不大合适了。如果有再版的话,我就修改一下。谢谢建议!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants