Skip to content

Commit b036344

Browse files
committed
Improve mutable-binding suggestion to include name
1 parent e6edf3a commit b036344

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3940,12 +3940,26 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
39403940
if let Some(decl) = local_decl
39413941
&& decl.can_be_made_mutable()
39423942
{
3943+
let message = 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+
format!("(mut {}) ", binding_name)
3953+
} else {
3954+
"mut ".to_string()
3955+
};
39433956
err.span_suggestion_verbose(
39443957
decl.source_info.span.shrink_to_lo(),
39453958
"consider making this binding mutable",
3946-
"mut ".to_string(),
3959+
message,
39473960
Applicability::MachineApplicable,
39483961
);
3962+
39493963
if !from_arg
39503964
&& matches!(
39513965
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)