Variables: Labeled Boxes
Imagine you have a stack of boxes. On each box you write a name with a marker, then you tuck something inside. Later, whenever you say the boxβs name, you get back what you put in it. In Rust, those boxes are called variables. π¦
Making a box with let
To make a variable, you use the magic word let. You give the box a name, then
an equals sign =, then the value you want to store inside.
let age = 10;
This says: βMake a box called age and put the number 10 inside.β The semicolon ;
at the end is like a period at the end of a sentence β it tells Rust youβre done with
that instruction.
Looking inside the box
Once youβve put something in a box, you can print it. To pop a variableβs value into
your message, use curly braces {} like a little window into the box.
See how {name} turned into Ferris and {age} turned into 10? Rust peeked inside
each box for you and dropped the value right into your sentence. π
color and store your favorite color in it, like
let color = "blue";. Then print a line that uses {color}.
Press βΆ Run!
Quick quiz
What does let score = 7; do?
Yes! let makes a named box (a variable) and stores a value inside it. π¦
let. You store a value
inside and grab it later by name, and you can print it with {}. Next up:
what happens when you want to change what's in a box! π