The following code compiles successfully:
let mut v = vec![1];
let r = &mut v;
r.push(r.len());
while this one fails:
let mut v = vec![1];
let r = &mut v;
r.push(v.len());
with error:
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
|
| let r = &mut v;
| ------ mutable borrow occurs here
| r.push(v.len());
| ^ immutable borrow occurs here
| r.push(r.len());
| - mutable borrow later used here
- Why the first example compiles correctly? Is it because the same reference:
r
is used in the outer and inner calls? Or is it because it applies the RFC 2025, Two-Phase Borrows? Or something else? - Why the second example fails given that the first example succeeds? Why the RFC 2025, Two-Phase Borrows does not apply here?
I suspect that in the first example there are no errors because the compiler does not create intermediate references and it uses the same reference: r
so that there are not multiple borrows.
However, if that is the case, why the following code fails to compile
let mut v = vec![1];
let r = &mut v;
r.push({r.push(0);1});