Variables and Mutability
Part 1 · Rust. Name your values with let, allow changes with mut, set fixed rules with const, and reuse names with shadowing, all at Rusty Bean Café.
In the last lesson we typed 450 every time we needed the price of a latte. That works for a tiny program, but imagine changing the price later and hunting down every 450. In this lesson you’ll learn to give values names, decide which values are allowed to change, and set café-wide rules that never change.
Variables with let
A variable is a name attached to a value. Think of the labelled jars behind the café counter: the label says “Sugar”, and the jar holds the sugar. In Rust, you make a variable with the keyword let:
fn main() { let cafe_name = "Rusty Bean Café"; let latte_price = 450; println!("Welcome to {cafe_name}!"); println!("A latte costs {latte_price} cents");}Welcome to Rusty Bean Café!A latte costs 450 centsStep by step:
let cafe_name = "Rusty Bean Café";creates a variable namedcafe_nameand stores the text in it. The=here means “store this value”, not “is equal to” like in maths class.let latte_price = 450;stores the number450(cents) inlatte_price.{cafe_name}insideprintln!is a placeholder with the variable’s name written straight inside the braces. Rust fills it with the variable’s value. This is the same as writingprintln!("Welcome to {}!", cafe_name);. Use whichever reads better.
Variable names use snake_case: lowercase words joined by underscores. Pick names that say what the value means. latte_price is far clearer than lp or x.
Variables can’t change by default
Now suppose the café raises the latte price. Let’s try changing the variable:
fn main() { let latte_price = 450; println!("A latte costs {} cents", latte_price); latte_price = 475; println!("Now it costs {} cents", latte_price);}Run cargo run, and the compiler refuses:
error[E0384]: cannot assign twice to immutable variable `latte_price` --> src/main.rs:4:5 |2 | let latte_price = 450; | ----------- first assignment to `latte_price`3 | println!("A latte costs {} cents", latte_price);4 | latte_price = 475; | ^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable |help: consider making this binding mutable |2 | let mut latte_price = 450; | +++Let’s read it:
- What went wrong: you tried to assign a value twice to an immutable variable. Immutable means “can’t be changed”.
- Where: line 4 of
src/main.rs. The---under line 2 shows where the variable got its first value. - How to fix it: the
help:section suggests addingmuton line 2.
In Rust, variables are immutable by default. Once a value is in the jar, the lid is glued shut. This sounds limiting, but it’s a safety feature. In a big program, if you know a value can’t change, you never have to wonder whether some other line quietly changed it.
Allowing change with mut
When a value should change, say so with mut (short for mutable, meaning “changeable”):
fn main() { let mut cups_sold = 0; println!("Cups sold: {cups_sold}");
cups_sold = cups_sold + 1; cups_sold += 2; println!("Cups sold: {cups_sold}");}Cups sold: 0Cups sold: 3let mut cups_sold = 0;creates a mutable variable starting at0.cups_sold = cups_sold + 1;reads the current value (0), adds 1, and stores the result (1) back in the jar. Notice there’s noletthis time: we’re changing an existing variable, not making a new one.cups_sold += 2;is a shortcut forcups_sold = cups_sold + 2;. Now it’s 3. There are matching shortcuts-=,*=and/=.
Tip
Start without mut, and only add it when the compiler tells you that you need it. If you add mut but never change the variable, Rust warns you: warning: variable does not need to be mutable. The compiler is helping you keep code honest about what changes.
Warning
mut lets you change a variable’s value, but not its type (the kind of value it holds). A variable that started as text can’t later hold a number. You’ll learn about types in the next lesson, and shadowing (below) is the way around this.
Constants with const
Some values are rules for the whole café: the maximum number of cups in one order, or opening time. They never change while the program runs. For these, use a constant:
const MAX_CUPS_PER_ORDER: u32 = 10;const OPENING_HOUR: u32 = 7;
fn main() { println!("We open at {OPENING_HOUR}:00."); println!("Max cups per order: {MAX_CUPS_PER_ORDER}");}We open at 7:00.Max cups per order: 10How constants differ from let variables:
- They use
constinstead oflet, and can never bemut. - Their names are SCREAMING_SNAKE_CASE: all capitals with underscores. This makes them easy to spot.
- You must write their type.
: u32means “a whole number that can’t be negative”. We’ll cover types properly in the next lesson. - They can live outside any function, like here above
main, so the whole program can use them. Think of them as rules painted on the café wall rather than notes in one barista’s pocket. - Their value must be known when the program is compiled. You can write
const SECONDS_PER_HOUR: u32 = 60 * 60;, but not a value that’s only known while running, like what a customer types in.
Shadowing: reusing a name
Rust lets you declare a new variable with the same name as an earlier one, using let again. The new one shadows (hides) the old one from that point on:
fn main() { let price = 450; let price = price + 50; println!("Price with oat milk: {price}");
{ let price = price * 2; println!("Two oat lattes: {price}"); } println!("Back to one: {price}");}Price with oat milk: 500Two oat lattes: 1000Back to one: 500- Line 2 creates
pricewith the value 450. - Line 3 creates a brand new variable, also called
price, using the old one to calculate 500. From here on,pricemeans the new one. - The inner
{ }braces make a scope: a region of code where names live. Inside it, anotherprice(1000) shadows the outer one. - When the inner scope ends at
}, itspricedisappears, and the outerprice(500) is visible again.
Shadowing vs. mut
They look similar, but they’re different:
- With
mut, you change the value inside the same jar. - With shadowing, you get a new jar with the same label. The old jar is hidden.
Because it’s a new variable, shadowing can even change the type. A common case is turning text into a number:
fn main() { let cups = "3"; let cups: u32 = cups.parse().unwrap(); println!("Cups after one more: {}", cups + 1);}Cups after one more: 4- The first
cupsis text:"3", like something a customer typed on a website. cups.parse()tries to turn the text into a number, and: u32says which kind of number we want..unwrap()means “give me the number, and stop the program if the text wasn’t a valid number”. It’s fine for now. You’ll learn safer ways in Option and Result.- The new
cupsis a real number, socups + 1works.
Note
Shadowing is handy when you transform a value step by step and the old version is no longer useful. You don’t need cups_text and cups_number, just cups.
Try it yourself
Write a program for the café’s morning stock count:
- A constant
DAILY_MILK_TARGETset to12(litres), with typeu32. - A mutable variable
milk_litresstarting at5. - A delivery arrives with
8more litres. Updatemilk_litresusing+=. - Print the current amount and the target, using
{}placeholders with the names inside.
Show solution
const DAILY_MILK_TARGET: u32 = 12;
fn main() { let mut milk_litres = 5; milk_litres += 8; println!("Milk in stock: {milk_litres} litres (target: {DAILY_MILK_TARGET})");}Output:
Milk in stock: 13 litres (target: 12)milk_litres needs mut because the delivery changes it. DAILY_MILK_TARGET is a café rule that never changes, so it’s a const.
Recap
letcreates a variable: a name attached to a value. Variables are immutable by default.- Add
mutwhen a value needs to change. Use+=,-=and friends as shortcuts. constvalues never change, need a type, use SCREAMING_SNAKE_CASE, and can live outside functions.- Shadowing (
letwith the same name) creates a new variable, which can even have a different type. - Inner
{ }blocks make a scope. Names created inside disappear at the closing brace.
What’s next
We’ve been storing numbers and text, but Rust cares a lot about exactly what kind of value each one is. Learn the building blocks in Data Types.
0 of 35 lessons complete