Skip to content

Commit 79a8499

Browse files
authored
Rollup merge of rust-lang#80941 - JohnTitor:ref-mut-pat-in-loops, r=varkor
Do not suggest invalid code in pattern with loop Fixes rust-lang#80913
2 parents b3aa880 + 4362da1 commit 79a8499

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

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

+4-1
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
141141
self.add_moved_or_invoked_closure_note(location, used_place, &mut err);
142142

143143
let mut is_loop_move = false;
144+
let mut in_pattern = false;
144145

145146
for move_site in &move_site_vec {
146147
let move_out = self.move_data.moves[(*move_site).moi];
@@ -256,6 +257,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
256257
"ref ".to_string(),
257258
Applicability::MachineApplicable,
258259
);
260+
in_pattern = true;
259261
}
260262

261263
if let Some(DesugaringKind::ForLoop(_)) = move_span.desugaring_kind() {
@@ -302,7 +304,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
302304
let place = &self.move_data.move_paths[mpi].place;
303305
let ty = place.ty(self.body, self.infcx.tcx).ty;
304306

305-
if is_loop_move {
307+
// If we're in pattern, we do nothing in favor of the previous suggestion (#80913).
308+
if is_loop_move & !in_pattern {
306309
if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind() {
307310
// We have a `&mut` ref, we need to reborrow on each iteration (#62112).
308311
err.span_suggestion_verbose(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Regression test for #80913.
2+
3+
fn main() {
4+
let mut x = 42_i32;
5+
let mut opt = Some(&mut x);
6+
for _ in 0..5 {
7+
if let Some(mut _x) = opt {}
8+
//~^ ERROR: use of moved value
9+
}
10+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0382]: use of moved value
2+
--> $DIR/move-in-pattern-mut-in-loop.rs:7:21
3+
|
4+
LL | if let Some(mut _x) = opt {}
5+
| ^^^^^^ value moved here, in previous iteration of loop
6+
|
7+
= note: move occurs because value has type `&mut i32`, which does not implement the `Copy` trait
8+
help: borrow this field in the pattern to avoid moving `opt.0`
9+
|
10+
LL | if let Some(ref mut _x) = opt {}
11+
| ^^^
12+
13+
error: aborting due to previous error
14+
15+
For more information about this error, try `rustc --explain E0382`.

0 commit comments

Comments
 (0)