Closed
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 variable
Desired 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 variable
Rationale 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