Skip to content

Suggest .swap() method on slice instead of std::mem::swap when latter causes conflicting borrows #102269

Closed
@5225225

Description

@5225225

Given the following code: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=599e18cde44ec5b1ebb113780f3e6487

pub fn swap(arr: &mut [u32; 2]) {
    std::mem::swap(&mut arr[0], &mut arr[1]);
}

The current output is:

   Compiling playground v0.0.1 (/playground)
error[E0499]: cannot borrow `arr[_]` as mutable more than once at a time
 --> src/lib.rs:2:33
  |
2 |     std::mem::swap(&mut arr[0], &mut arr[1]);
  |     -------------- -----------  ^^^^^^^^^^^ second mutable borrow occurs here
  |     |              |
  |     |              first mutable borrow occurs here
  |     first borrow later used by call

For more information about this error, try `rustc --explain E0499`.
error: could not compile `playground` due to previous error

I'd expect a help: or similar suggesting a replacement with arr.swap(0, 1).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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