Shouldn't reassigning to a different mutably borrowed variable unborrow previous variable?


#1

I’m new to Rust and playing around with borrowing I ran into an interesting issue: It seem like the borrow checker is overly pessimistic when I reassign a mutable reference to mutably borrow from a different variable. It doesn’t seem to realize that this re-assignment unborrows the previously borrowed variable. The following snippet shows what I mean:

fn main()
{
    let mut x = 1;
    let mut z = 0;
    let mut y = &mut x;
    y = &mut z;
    println!("{}", x);
    println!("{}", z);
}

I would expect the compiler to just flag ‘z’ as being mutably borrowed when the println tries to immutably borrow it. Immutably borrowing ‘x’ for printing should be OK. However, I get the following errors:

error: cannot borrow `x` as immutable because it is also borrowed as mutable [E0502]
<std macros>:2:25: 2:56 note: in this expansion of format_args!
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
...
error: cannot borrow `z` as immutable because it is also borrowed as mutable [E0502]
<std macros>:2:25: 2:56 note: in this expansion of format_args!
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
...
error: aborting due to 2 previous errors

Am I missing something?


#2

Unfortunately, borrow scopes are currently equivalent to lexical scopes. Work is ongoing to improve this, but in the mean time you’ll have to create a new lexical scope if you want to “unborrow” something:

fn main()
{
    let mut x = 1;
    let mut z = 0;
    {
        let mut y = &mut x;
    }
    let mut y = &mut z;
    println!("{}", x);
}