Part 01 · Rust Is Not Scary

Variables and mut

letmutShadowingConstants

Variables in Rust cannot change unless you say so with mut. Why that small rule saves you from a whole class of bugs.

⏱ 9 min · Station 5 of 75

The story

Walk into any shop and look at two kinds of labels. The price printed on a packet of biscuits never changes: the factory printed ৳20 and that is that. The whiteboard by the counter that says "Today's eggs: ৳150 a dozen" gets wiped and rewritten whenever the price moves.

Rust makes you say which kind of label each value is. By default, every variable is a printed label: once set, it stays. If you want a whiteboard, you have to ask for one with the word mut. That small rule sounds annoying, and it turns out to prevent a whole family of bugs.

The idea

A variable gives a name to a value. In Rust you make one with let:

let price = 420;

Three tools cover everything you'll do with variables:

  1. let: a value that does not change. This is the default, and most variables in real Rust code are like this.
  2. let mut: a value you plan to change, like a running total. mut is short for mutable, "can be changed".
  3. Shadowing: a new let with the same name. It makes a new variable that hides the old one. It is how you turn text into a number while keeping a sensible name.

And one relative: const, a value fixed forever and known before the program even runs, such as a delivery fee. Constants are written in CAPITALS and always need a type.

letlet mutshadowingprice = 420450error[E0384]: cannot assign twicetotal= 0= 420= 605= 665+ 420+ 185+ 60same box, new valuequantity = "3"textparse()quantity = 3numbernew box, same name
let refuses a new value, let mut takes new values in the same box, and shadowing makes a brand new box with the same name.

Try it: a running total

A cart total changes as items go in, so it needs mut. The delivery fee never changes, so it is a const:

const DELIVERY_FEE: u32 = 60;

fn main() {
    let rice = 420;
    let oil = 185;

    let mut total = 0;
    total = total + rice;
    println!("after rice: {total}");
    total += oil; // short for total = total + oil
    println!("after oil:  {total}");
    total += DELIVERY_FEE;
    println!("with delivery: {total}");
}
after rice: 420
after oil:  605
with delivery: 665

rice and oil never change, so they are plain let. Only total changes, so only total is mut. Anyone reading this code knows at a glance which values move and which don't.

Now shadowing. A customer types how many dozen eggs they want. What you get from the keyboard is text ("3"), but you need a number to multiply:

fn main() {
    let quantity = "3"; // what the customer typed: text
    let quantity: u32 = quantity.parse().expect("not a number");
    // same name, new variable, now a number
    let total = quantity * 150;
    println!("{quantity} dozen eggs cost {total} taka");

    let total = total + 60; // shadow again: add delivery
    println!("with delivery: {total}");
}
Predict first

The second let total = total + 60; runs. What happened to the first total?

3 dozen eggs cost 450 taka
with delivery: 510

Notice the first shadow even changed the type: quantity started as text and became a u32 number. With mut you couldn't do that; a mut variable keeps its type forever.

What the compiler says

Forget that let means "printed label", and try to change the price:

fn main() {
    let price = 420;
    println!("price: {price}");
    price = 450; // the shop raises the price
    println!("new price: {price}");
}
error[E0384]: cannot assign twice to immutable variable `price`
 --> src/main.rs:4:5
  |
2 |     let price = 420;
  |         ----- first assignment to `price`
3 |     println!("price: {price}");
4 |     price = 450; // the shop raises the price
  |     ^^^^^^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     let mut price = 420;
  |         +++

For more information about this error, try `rustc --explain E0384`.
error: could not compile `immutable` (bin "immutable") due to 1 previous error
  • error[E0384]: cannot assign twice to immutable variable `price` : you gave price a value once, and you're trying to give it another.
  • The ----- under line 2 marks the first assignment, and the ^^^^ under line 4 marks the second. The compiler shows you both ends of the problem.
  • help: consider making this binding mutable: if you really meant to change it, add mut. The +++ shows exactly where.

But think before you take the help. Was changing price the plan? In a real shop the price of an order already placed should not change, so maybe the right fix is a new variable, let new_price = 450;, not mut. The compiler offers the quick fix; you decide what the code should mean.

The same rule protects things like lists. A list (Vec) you didn't mark mut can't be pushed to:

fn main() {
    let cart = Vec::new();
    cart.push("rice");
    println!("{cart:?}");
}
error[E0596]: cannot borrow `cart` as mutable, as it is not declared as mutable
 --> src/main.rs:3:5
  |
3 |     cart.push("rice");
  |     ^^^^ cannot borrow as mutable
  |
help: consider changing this to be mutable
  |
2 |     let mut cart = Vec::new();
  |         +++

For more information about this error, try `rustc --explain E0596`.
error: could not compile `cart` (bin "cart") due to 1 previous error

"Not declared as mutable" means the same thing: nothing in Rust changes unless you said it could.

Under the hood

Why make "can't change" the default? Because most bugs that involve a variable are about who changed it and when. If a value can't change, you never have to ask. You read let price = 420; at the top of a 200-line function and you know it is still 420 at the bottom. No need to read the 200 lines in between.

The compiler also works the other way. If you write mut but never change the value, it warns you, so mut keeps meaning something:

fn main() {
    let mut price = 420;
    println!("price: {price}");
}
warning: variable does not need to be mutable
 --> src/main.rs:2:9
  |
2 |     let mut price = 420;
  |         ----^^^^^
  |         |
  |         help: remove this `mut`
  |
  = note: `#[warn(unused_mut)]` (part of `#[warn(unused)]`) on by default

A warning is not an error: the program still builds. It is the compiler saying "this works, but it is probably not what you meant".

Three more details worth knowing:

  • Shadowing costs nothing at runtime. It is just a new name for a new value; in an optimized build the compiler is free to reuse the same memory.
  • const is not a variable at all. The compiler pastes its value into every place it's used, so DELIVERY_FEE doesn't exist as a box in memory while the program runs.
  • let must be set before use. Rust won't let you read a variable that might not have a value yet, so there is no "undefined" like in JavaScript.

Compared with other languages

JavaScript has const, which looks like Rust's let. It isn't quite the same:

const cart = [];
cart.push("rice"); // allowed: const only locks the name, not the array
console.log(cart);
cart = ["oil"]; // not allowed: this changes what the name points to
[ 'rice' ]
/home/you/rust-lab/cart.js:4
cart = ["oil"]; // not allowed: this changes what the name points to
     ^

JavaScript's const only locks the name: cart must always point at the same array, but anyone can push into that array. Rust's plain let locks the value too, which is why cart.push failed above. Also notice when each error appears: JavaScript printed [ 'rice' ] first and failed on line 4 while running. Rust failed before anything ran.

PythonJavaScriptGoRust
Defaulteverything can changelet changes, const locks the nameeverything can changenothing changes
Change a valuejust assignletjust assignlet mut
Fixed foreverconvention: CAPSconst (name only)constconst
Same name, new valuejust assignnot allowed with let:= in a new blockshadowing

Key takeaway

In Rust, variables don't change unless you say mut. Plain let for values that stay, let mut for running totals and counters, shadowing (let again with the same name) when you transform a value into a new one, and const for fixed numbers like a delivery fee. The compiler enforces it both ways: changing a plain let is an error, and an unneeded mut is a warning. So mut in Rust code is a signal: "watch this one, it moves".

Practice

Objective: use let, let mut, shadowing and const in one small program.

Challenge: build a bill for three items (rice ৳420, oil ৳185, eggs ৳150) with a mut total. Then shadow total to apply a 10% discount (integer maths is fine), and shadow it again to add a const DELIVERY_FEE of ৳60. Print the total after each step.

Expected result:

items:     755
after 10%: 680
to pay:    740
Hint 1

const DELIVERY_FEE: u32 = 60; goes above fn main, and needs its type.

Hint 2

Start with let mut total = 0; and add each item with total += ...;.

Hint 3

10% off is total - total / 10. Write it as let total = total - total / 10; so it is a new total and no longer needs mut.

Solution
const DELIVERY_FEE: u32 = 60;

fn main() {
    let mut total = 0;
    total += 420; // rice 5kg
    total += 185; // soybean oil
    total += 150; // eggs (12)
    println!("items:     {total}");

    let total = total - total / 10; // 10% off, a new `total` shadows the old one
    println!("after 10%: {total}");

    let total = total + DELIVERY_FEE;
    println!("to pay:    {total}");
}

Why 680 and not 679.50? 755 / 10 is 75, not 75.5, because dividing two whole numbers in Rust gives a whole number. The next lesson is all about that: which number type to choose, and what happens at the edges.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →