Open
Description
Currently with Rust 2018, this code does not compile.
fn main() {
let mut v = vec![1, 2, 3];
v.swap(0, v.len() - 1);
assert_eq!(v, &[3, 2, 1]);
}
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
|
3 | v.swap(0, v.len() - 1);
| - ---- ^ immutable borrow occurs here
| | |
| | mutable borrow later used by call
| mutable borrow occurs here
It seems that the compiler desugars the method call like this:
let v0 = &*v;
let v1 = &mut *v;
let arg0 = 0;
let arg1 = v0.len() - 1; // v1 is still alive here
v1.swap(arg0, arg1);
But I think the DerefMut
should be deferred, or use only DerefMut
reference without any Deref
.
let v0 = &*v;
let arg0 = 0;
let arg1 = v0.len() - 1; // no mutable borrows here
let v1 = &mut *v;
v1.swap(arg0, arg1);
let v0 = &mut *v;
let arg0 = 0;
let arg1 = v0.len() - 1;
v0.swap(arg0, arg1);