Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0384: cannot assign twice to immutable variable
What it meansVariables are immutable by default. You assigned to one twice without declaring it mut.
What rustc prints
error[E0384]: cannot assign twice to immutable variable `x` --> main.rs:3:5 | 2 | let x = 3; | - first assignment to `x` 3 | x = 5; // error, reassignment of immutable variable | ^^^^^ cannot assign twice to immutable variable | help: consider making this binding mutable | 2 | let mut x = 3; | +++
Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
Why it happens
- A counter or accumulator declared with
letinstead oflet mut. - Reassigning a function parameter.
How to fix it
1. Add mut
let mut count = 0;
count += 1;2. Shadow instead
A new let with the same name is a new variable.
let input = input.trim();Other wordings of this error
cannot assign twice to immutable variable, first assignment to, help: consider making this binding mutable
The compiler team's explanation
An immutable variable was reassigned.
Erroneous code example:
fn main() {
let x = 3;
x = 5; // error, reassignment of immutable variable
}
By default, variables in Rust are immutable. To fix this error, add the keyword mut after the keyword let when declaring the variable. For example:
fn main() {
let mut x = 3;
x = 5;
}
Alternatively, you might consider initializing a new variable: either with a new bound name or (by shadowing) with the bound name of your existing variable. For example:
fn main() {
let x = 3;
let x = 5;
}From rustc --explain E0384 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0382borrow of moved value
- E0499cannot borrow as mutable more than once at a time
- E0502cannot borrow as mutable because it is also borrowed as immutable
- E0106missing lifetime specifier
- E0373closure may outlive the current function, but it borrows
- E0392type parameter `T` is never used
- E0476lifetime of the source pointer does not outlive lifetime bound of the object type
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?