Start learning free

LESSON 14 OF 348 · VARIABLES

let, mut and Shadowing in Rust in Rust

Lesson

In most languages, a variable can be changed whenever you like. Rust flips that default: every let binding is immutable — once you give it a value, that value is final. This is not a limitation, it's a safety feature: if a value is never supposed to change, the compiler now guarantees it never does, and whole categories of bugs disappear before the program even runs.

When you genuinely need a value to change — a counter, a running total — you opt in to mutation by writing let mut:

let mut score = 0;
score += 10;    // OK — score was declared with mut
println!("{}", score);

The trap:

Sooner or later, every Rust beginner writes an assignment to a plain let binding. The compiler stops you with this exact error — read it carefully, because it also tells you the fix:

error[E0384]: cannot assign twice to immutable variable `clicks`
 --> src/main.rs:3:5
  |
2 |     let clicks = 0;
  |         ------ first assignment to `clicks`
3 |     clicks += 1;
  |     ^^^^^^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     let mut clicks = 0;
  |         +++

The help: line is the compiler literally handing you the solution: add mut.


Shadowing — rebinding without mutating:

There is a second way to "change" a variable that needs no mut at all: write a new let with the same name. This is called shadowing. It doesn't modify the old value — it creates a fresh binding that hides the old one. Because it's a brand-new binding, it can even have a different type:

let input = "7";                          // input is a &str (text)
let input: i32 = input.parse().unwrap();  // input is now an i32 (number)
println!("{}", input + 1);                // prints 8

.parse() converts text into a number; the : i32 annotation tells it which kind of number, and .unwrap() takes the value out (fine here, since we know the text is numeric). Mutation with mut can never change a variable's type — shadowing is the idiomatic way to convert a value and keep its name.


Assignment
Follow the Coding Tutorial to build a tiny click counter, then convert a text label into a number:

  • Declare a mutable counter clicks starting at 0, increment it twice with +=, and print it.
  • Declare label as the string "42", shadow it into an i32 using .parse().unwrap(), and print its double.

The exact expected output is:

clicks = 2
label doubled = 84

Hint
If the compiler says cannot assign twice to immutable variable, you forgot mut. If it asks about a type it "cannot infer", give the new binding an explicit : i32.


STEP 1 OF 7
    Ctrl + Enter to check

    Let Mut And Shadowing in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free