Rust E0384 "cannot assign twice to immutable variable" in CI
You assigned a new value to a binding that is immutable. Rust bindings are immutable by default, so a second assignment without mut is rejected.
What this error means
The compiler reports error[E0384]: cannot assign twice to immutable variable total`` at the reassignment. It is deterministic.
cargo
error[E0384]: cannot assign twice to immutable variable `total`
--> src/sum.rs:4:5
|
2 | let total = 0;
| ----- first assignment to `total`
...
4 | total = total + n;
| ^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variableCommon causes
Reassigning an immutable binding
A let total = 0; is immutable; total = ... later is a second assignment, which Rust forbids without mut.
Intending to shadow instead
If you wanted a fresh binding, you needed let total = ... again, not a bare assignment.
How to fix it
Declare the binding mut
Make the variable mutable if it is genuinely meant to change.
src/sum.rs
let mut total = 0;
for n in nums { total += n; }Shadow with a new let
If each value is a distinct binding, rebind with let.
src/sum.rs
let total = compute_base();
let total = total + adjustment;How to prevent it
- Use
mutfor accumulators and counters that change in place. - Use shadowing (
let x = ...again) for staged transformations. - Rely on rust-analyzer to catch the reassignment early.
Related guides
Rust E0596 "cannot borrow as mutable" in CIFix rust E0596 "cannot borrow `x` as mutable, as it is not declared as mutable" in CI -- a binding needs `mut…
Rust "error[E0502]: cannot borrow as mutable" in CIFix Rust "error[E0502]: cannot borrow X as mutable because it is also borrowed as immutable" in CI -- overlap…
Rust "unused variable" Denied as Error (-D warnings) in CIFix Rust builds where "unused variable" (or other lints) fail CI under -D warnings / deny(warnings) -- the wa…