Solving `cannot assign twice to immutable variable` in Rust
December 20, 2021 ‐ 2 min read
If you encountered the error cannot assign twice to immutable variable
you most likely tried to reassign a value to an immutable variable. Variables in Rust are by default immutable, meaning that the variable only gets a value assigned at the time that the variable is declared.
Consider the following main function for example, in which we create variable a
and set its value to 0
. On the next line we try to set the value of a
to 1
.
fn main() {
let a = 0;
a = 1;
}
This code spawns the following error:
error[E0384]: cannot assign twice to immutable variable `a`
--> src/main.rs:3:5
|
2 | let a = 0;
| -
| |
| first assignment to `a`
| help: consider making this binding mutable: `mut a`
3 | a = 1;
| ^^^^^ cannot assign twice to immutable variable
For more information about this error, try `rustc --explain E0384`.
In order to fix this problem we have two options available:
- Make the variable mutable.
- Rewrite the code so that you don’t need to reassign a value to an immutable variable.
Let's stick to the first option for now; declaring a mutable variable. Which is also the suggestion given to us by the Rust compiler. In order to declare a mutable variable in Rust you use the mut
keyword after let
, mut
being short for mutable.
So in order to solve the problem as seen in the previous example we can rewrite our program as follows:
fn main() {
let mut a = 0;
a = 1;
}
Immutable variables cannot be modified once they have been declared. This is one of Rust’s features that provide your code with type safety. However, sometimes mutable variables are just very convenient.