-
Notifications
You must be signed in to change notification settings - Fork 13.9k
Closed
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.
Description
Code
fn main() {
let y = Some(0);
if let Some(x) = y {
x = 2;
}
}Current output
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:9
|
3 | if let Some(x) = y {
| -
| |
| first assignment to `x`
| help: consider making this binding mutable: `mut x`
4 | x = 2;
| ^^^^^ cannot assign twice to immutable variableDesired output
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:9
|
3 | if let Some(x) = y {
| -
| |
| first assignment to `x`
| help: consider making this binding mutable: `mut x`
| help: to modify the original value, take a borrow instead: `ref mut x`
4 | x = 2;
| ^^^^^ cannot assign twice to immutable variableRationale and extra context
In the original code, it's unclear whether the intention is to modify the contents of y or only the copy contained in x. The suggestion assumes the second case, which gives:
fn main() {
let y = Some(0);
if let Some(mut x) = y {
x = 2;
}
}This doesn't modify y yet compiles fine, which I expect could be surprising to a beginner. This meaning of mut is far from obvious. With the updated error message, subsequent errors guide the user to actually modifying y.
Other cases
No response
Anything else?
No response
Metadata
Metadata
Assignees
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.