πŸ”’
World 3 Β· Building Blocks

Locked & Unlocked Boxes

In Rust, some boxes come with a tiny lock on them. Once you put something inside, the lid clicks shut and you can’t swap it for something new. That sounds strict β€” but it’s one of the ways Rust keeps your programs safe! πŸ”’

Locked boxes (the normal kind)

When you make a variable the regular way with let, it is locked. The fancy word for β€œcan’t be changed” is immutable. Once you set the value, it stays that way.

let stars = 3;
stars = 5; // ❌ Nope! The box is locked.

Rust would stop you right there with a friendly error. That’s on purpose β€” it stops you from accidentally changing something you didn’t mean to.

New word Immutable means "cannot be changed." A normal let box is immutable β€” locked tight.

Unlocked boxes with let mut

What if you really DO want to change the value? Then you ask for an unlocked box by adding the word mut (short for mutable, which means β€œcan change”). Now you can open the lid and swap the value anytime.

The box started with 0, then we opened it and put 100 inside. Because we used mut, Rust said β€œsure, go ahead!” πŸŽ‰

Think of it like this… A normal box is like a sealed time capsule β€” once it's shut, it stays shut. A mut box is like your backpack β€” you can take things out and put new things in whenever you like.

Boxes that NEVER change: const

Some things should never, ever change β€” like the number of days in a week. For those, Rust has const (short for constant). You write the name in SHOUTY capitals so everyone knows it stays the same forever.

const DAYS_IN_WEEK: i32 = 7;
Ferris says: Start every box locked. Only add mut when you truly need to change it. Fewer surprises means fewer bugs! πŸ¦€
Try this! Change the program so score starts at 10, then change it to 50. Print it before and after. Press β–Ά Run!

Quick quiz

Which word makes a box you're allowed to change?

Right! let mut gives you an unlocked box you can change later. πŸ”“

You learned… Normal let boxes are locked (immutable), let mut makes a box you can change, and const is for values that never change. Next up: the different kinds of stuff you can put in a box! πŸ”’