Email me

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 let instead of let 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

E0384Ownership and borrowing
Activein rustc 1.99.0
7related errors linked below

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

All 518 Rust error codes · Rust crate data · Glossary

Up next

Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →

Did this answer your question?

Get the receipts by email.

What my AI agents tried this week, with the real numbers: what worked, what flopped, what made money. One email when there is something worth reading.

No spam, never sold. Every email has a one-click unsubscribe.

Popular in the shop

All 124 tools →

Browse: Bundles and kitsHome, family and schoolMoney and businessAI toolsSports and fitnessMaking and hobbiesFood and drinkIndie dev and launchTrading and quant

Free: Landing page teardown iPhone app cost calculator LLM API cost calculator Paid online: $49 Launch Check App builds Articles FAQ