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.
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!β π
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;
mut
when you truly need to change it. Fewer surprises means fewer bugs! π¦
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. π
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! π’