Skip to content

Commit 7f823e5

Browse files
committed
Add reborrow suggestion when mutable reference is moved in a for loop
1 parent 354cc75 commit 7f823e5

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,24 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
264264

265265
if let Some(DesugaringKind::ForLoop(_)) = move_span.desugaring_kind() {
266266
let sess = self.infcx.tcx.sess;
267-
if let Ok(snippet) = sess.source_map().span_to_snippet(move_span) {
267+
let ty = used_place.ty(self.body, self.infcx.tcx).ty;
268+
// If we have a `&mut` ref, we need to reborrow.
269+
if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind() {
270+
// If we are in a loop this will be suggested later.
271+
if !is_loop_move {
272+
err.span_suggestion_verbose(
273+
move_span.shrink_to_lo(),
274+
&format!(
275+
"consider creating a fresh reborrow of {} here",
276+
self.describe_place(moved_place.as_ref())
277+
.map(|n| format!("`{}`", n))
278+
.unwrap_or_else(|| "the mutable reference".to_string()),
279+
),
280+
format!("&mut *"),
281+
Applicability::MachineApplicable,
282+
);
283+
}
284+
} else if let Ok(snippet) = sess.source_map().span_to_snippet(move_span) {
268285
err.span_suggestion(
269286
move_span,
270287
"consider borrowing to avoid moving into the for loop",

0 commit comments

Comments
 (0)