Skip to content

Commit ad4efba

Browse files
committed
Improve mutable-binding suggestion to include name
1 parent 5dbf406 commit ad4efba

File tree

3 files changed

+50
-6
lines changed

3 files changed

+50
-6
lines changed

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3940,12 +3940,29 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
39403940
if let Some(decl) = local_decl
39413941
&& decl.can_be_made_mutable()
39423942
{
3943-
err.span_suggestion_verbose(
3944-
decl.source_info.span.shrink_to_lo(),
3945-
"consider making this binding mutable",
3946-
"mut ".to_string(),
3947-
Applicability::MachineApplicable,
3948-
);
3943+
if matches!(
3944+
decl.local_info(),
3945+
LocalInfo::User(BindingForm::Var(VarBindingForm {
3946+
opt_match_place: Some((_, match_span)),
3947+
..
3948+
})) if matches!(match_span.desugaring_kind(), Some(DesugaringKind::ForLoop))
3949+
) && let Ok(binding_name) =
3950+
self.infcx.tcx.sess.source_map().span_to_snippet(decl.source_info.span)
3951+
{
3952+
err.span_suggestion_verbose(
3953+
decl.source_info.span.shrink_to_lo(),
3954+
"consider making this binding mutable",
3955+
format!("(mut {}) ", binding_name),
3956+
Applicability::MachineApplicable,
3957+
);
3958+
} else {
3959+
err.span_suggestion_verbose(
3960+
decl.source_info.span.shrink_to_lo(),
3961+
"consider making this binding mutable",
3962+
"mut ".to_string(),
3963+
Applicability::MachineApplicable,
3964+
);
3965+
}
39493966
if !from_arg
39503967
&& matches!(
39513968
decl.local_info(),
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
fn main() {
2+
let nums: &[u32] = &[1, 2, 3];
3+
for &num in nums {
4+
num *= 2; //~ ERROR cannot assign twice to immutable variable `num`
5+
println!("{num}");
6+
}
7+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error[E0384]: cannot assign twice to immutable variable `num`
2+
--> $DIR/borrowck-for-loop-deref-pattern-assignment.rs:4:9
3+
|
4+
LL | for &num in nums {
5+
| --- first assignment to `num`
6+
LL | num *= 2;
7+
| ^^^^^^^^ cannot assign twice to immutable variable
8+
|
9+
help: consider making this binding mutable
10+
|
11+
LL | for &(mut num) num in nums {
12+
| +++++++++
13+
help: to modify the original value, take a borrow instead
14+
|
15+
LL | for &ref mut num in nums {
16+
| +++++++
17+
18+
error: aborting due to 1 previous error
19+
20+
For more information about this error, try `rustc --explain E0384`.

0 commit comments

Comments
 (0)