Skip to content

DerefMut borrow method call is too long with Deref arguments #57376

Open
@tirr-c

Description

@tirr-c

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-NLLArea: Non-lexical lifetimes (NLL)NLL-completeWorking towards the "valid code works" goalP-mediumMedium priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions