Skip to content

Commit 6c22e04

Browse files
authored
Rollup merge of #111403 - y21:suggest-slice-swap, r=compiler-errors
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
2 parents 016c306 + 679c5be commit 6c22e04

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

Diff for: compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -982,7 +982,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
982982
&msg_borrow,
983983
None,
984984
);
985-
self.suggest_split_at_mut_if_applicable(
985+
self.suggest_slice_method_if_applicable(
986986
&mut err,
987987
place,
988988
issued_borrow.borrowed_place,
@@ -1262,7 +1262,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
12621262
);
12631263
}
12641264

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

Diff for: tests/ui/suggestions/suggest-split-at-mut.stderr

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ LL | *a = 5;
99
| ------ first borrow later used here
1010
|
1111
= help: consider using `.split_at_mut(position)` or similar method to obtain two mutable non-overlapping sub-slices
12+
= help: consider using `.swap(index_1, index_2)` to swap elements at the specified indices
1213

1314
error: aborting due to previous error
1415

0 commit comments

Comments
 (0)