Skip to content

Bad code-section example #109

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

Open
NoamRodrik opened this issue Jul 10, 2021 · 2 comments
Open

Bad code-section example #109

NoamRodrik opened this issue Jul 10, 2021 · 2 comments

Comments

@NoamRodrik
Copy link

NoamRodrik commented Jul 10, 2021

Hey! I'm a beginner, but something worked and on the guide it said it shouldn't have worked.

On the "Borrowing Pointers" section, we've been given this code section:

fn foo() {
    let mut x = 5;            // type: i32
    {
        let y = &mut x;       // type: &mut i32
        //x = 4;              // Error - x has been borrowed
        //println!("{}", x);  // Error - requires borrowing x
    }
    x = 4;                    // OK - y no longer exists
}

First, on lines x = 4 and println!... the comment is a direct contradiction.
Second, uncommenting the println! does work. I'm not sure what that means though, but
something here is unclear.

EDIT: This is also true when uncommenting x = 4. I'm not really sure about the validity of this example.

Thank you!

@nrc
Copy link
Owner

nrc commented Aug 1, 2021

I think this is a result of changing from lexical to non-lexical lifetimes, previously lifetimes would always continue to the end of explicit scopes (mostly that means to a }), now however, lifetimes are terminated as soon as they can be. We could fix the example (i.e., cause the commented lines to be errors again) by adding a use of y after the commented lines and before the } on it's own line, e.g.:

fn foo() {
    let mut x = 5;            // type: i32
    {
        let y = &mut x;       // type: &mut i32
        //x = 4;              // Error - x has been borrowed
        //println!("{}", x);  // Error - requires borrowing x
        println!("{}", y);
    }
    x = 4;                    // OK - y no longer exists
}

(I think, I haven't actually verified this :-) )

@nrc
Copy link
Owner

nrc commented Aug 1, 2021

In fact, we could now remove the inner { ... } scope entirely.

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