]> git.lizzy.rs Git - rust.git/commitdiff
Add reborrow suggestion when mutable reference is moved in a for loop
authorGiacomo Stevanato <giaco.stevanato@gmail.com>
Tue, 6 Apr 2021 19:39:44 +0000 (21:39 +0200)
committerGiacomo Stevanato <giaco.stevanato@gmail.com>
Tue, 6 Apr 2021 19:39:44 +0000 (21:39 +0200)
compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs

index d5deec820889ac05595d459789de888bf53970de..5fdf8a8d1ee195d322f79af77cb250f5b6888707 100644 (file)
@@ -264,7 +264,24 @@ pub(in crate::borrow_check) fn report_use_of_moved_or_uninitialized(
 
                 if let Some(DesugaringKind::ForLoop(_)) = move_span.desugaring_kind() {
                     let sess = self.infcx.tcx.sess;
-                    if let Ok(snippet) = sess.source_map().span_to_snippet(move_span) {
+                    let ty = used_place.ty(self.body, self.infcx.tcx).ty;
+                    // If we have a `&mut` ref, we need to reborrow.
+                    if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind() {
+                        // If we are in a loop this will be suggested later.
+                        if !is_loop_move {
+                            err.span_suggestion_verbose(
+                                move_span.shrink_to_lo(),
+                                &format!(
+                                    "consider creating a fresh reborrow of {} here",
+                                    self.describe_place(moved_place.as_ref())
+                                        .map(|n| format!("`{}`", n))
+                                        .unwrap_or_else(|| "the mutable reference".to_string()),
+                                ),
+                                format!("&mut *"),
+                                Applicability::MachineApplicable,
+                            );
+                        }
+                    } else if let Ok(snippet) = sess.source_map().span_to_snippet(move_span) {
                         err.span_suggestion(
                             move_span,
                             "consider borrowing to avoid moving into the for loop",