r4cppp icon indicating copy to clipboard operation
r4cppp copied to clipboard

Bad example in "Borrowed Pointers"?

Open ThirteenPeeps opened this issue 5 years ago • 1 comments

The example given is:

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

But when I tested this, uncommenting the x = 4 line, it built and ran just fine. The same was true for the next example where y = &mut x: when I uncommented the two releavant lines it still ran.

I think either this is a bad example of the concept you were trying to communicate (borrowed values becoming temporarily immutable), or the concept has been changed over time and the material should be updated.

HOWEVER I am just learning Rust, so I may be utterly mistaken :)

ThirteenPeeps avatar May 29 '20 04:05 ThirteenPeeps

Huh, presumably due to non-lexical lifetimes. I think changing println!("{}", x); to println!("{}", y); should fix this, although maybe we should add rather than replace so that the comment on that line still makes sense

nrc avatar Jun 03 '20 07:06 nrc