Skip to content

Commit

Permalink
Rollup merge of #111403 - y21:suggest-slice-swap, r=compiler-errors
Browse files Browse the repository at this point in the history
suggest `slice::swap` for `mem::swap(&mut x[0], &mut x[1])` borrowck error

Recently saw someone ask why this code (example slightly modified):
```rs
fn main() {
  let mut foo = [1, 2];
  std::mem::swap(&mut foo[0], &mut foo[1]);
}
```
triggers this error and how to fix it:
```
error[E0499]: cannot borrow `foo[_]` as mutable more than once at a time
 --> src/main.rs:4:33
  |
4 |     std::mem::swap(&mut foo[0], &mut foo[1]);
  |     -------------- -----------  ^^^^^^^^^^^ second mutable borrow occurs here
  |     |              |
  |     |              first mutable borrow occurs here
  |     first borrow later used by call
  |
  = help: consider using `.split_at_mut(position)` or similar method to obtain two mutable non-overlapping sub-slices
```
The current help message is nice and goes in the right direction, but I think we can do better for this specific instance and suggest `slice::swap`, which makes this compile
  • Loading branch information
matthiaskrgr authored Jun 30, 2023
2 parents 016c306 + 679c5be commit 6c22e04
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
7 changes: 4 additions & 3 deletions compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -982,7 +982,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
&msg_borrow,
None,
);
self.suggest_split_at_mut_if_applicable(
self.suggest_slice_method_if_applicable(
&mut err,
place,
issued_borrow.borrowed_place,
Expand Down Expand Up @@ -1262,7 +1262,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
);
}

fn suggest_split_at_mut_if_applicable(
fn suggest_slice_method_if_applicable(
&self,
err: &mut Diagnostic,
place: Place<'tcx>,
Expand All @@ -1274,7 +1274,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
err.help(
"consider using `.split_at_mut(position)` or similar method to obtain \
two mutable non-overlapping sub-slices",
);
)
.help("consider using `.swap(index_1, index_2)` to swap elements at the specified indices");
}
}

Expand Down
1 change: 1 addition & 0 deletions tests/ui/suggestions/suggest-split-at-mut.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ LL | *a = 5;
| ------ first borrow later used here
|
= help: consider using `.split_at_mut(position)` or similar method to obtain two mutable non-overlapping sub-slices
= help: consider using `.swap(index_1, index_2)` to swap elements at the specified indices

error: aborting due to previous error

Expand Down

0 comments on commit 6c22e04

Please sign in to comment.