nrc / r4cppp

Rust for C++ programmers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bad code-section example

NoamRodrik opened this issue · comments

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!

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 :-) )

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