Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
5225225 opened this issue Sep 25, 2022 · 0 comments · Fixed by #120126
Labels
A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@5225225
Copy link
Contributor

5225225 commented Sep 25, 2022

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

@5225225 5225225 added A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Sep 25, 2022
@bors bors closed this as completed in c851150 Jan 20, 2024
rust-timer added a commit to rust-lang-ci/rust that referenced this issue Jan 20, 2024
Rollup merge of rust-lang#120126 - sjwang05:issue-102269, r=compiler-errors

Suggest `.swap()` when encountering conflicting borrows from `mem::swap` on a slice

This PR modifies the existing suggestion by matching on `[ProjectionElem::Deref, ProjectionElem::Index(_)]` instead of just `[ProjectionElem::Index(_)]`, which caused us to miss many cases. Additionally, it adds a more specific, machine-applicable suggestion in the case we determine `mem::swap` was used to swap elements in a slice.

Closes rust-lang#102269
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant