4 / 35

Rust Basics· 11 min read· Lesson 4 of 35

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:

src/main.rs
fn main() {
let cafe_name = "Rusty Bean Café";
let latte_price = 450;
println!("Welcome to {cafe_name}!");
println!("A latte costs {latte_price} cents");
}
Output
Welcome to Rusty Bean Café!
A latte costs 450 cents

Step by step:

  1. let cafe_name = "Rusty Bean Café"; creates a variable named cafe_name and stores the text in it. The = here means “store this value”, not “is equal to” like in maths class.
  2. let latte_price = 450; stores the number 450 (cents) in latte_price.
  3. {cafe_name} inside println! 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 writing println!("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:

src/main.rs
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:

Output
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:

  1. What went wrong: you tried to assign a value twice to an immutable variable. Immutable means “can’t be changed”.
  2. Where: line 4 of src/main.rs. The --- under line 2 shows where the variable got its first value.
  3. How to fix it: the help: section suggests adding mut on 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”):

src/main.rs
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}");
}
Output
Cups sold: 0
Cups sold: 3
  1. let mut cups_sold = 0; creates a mutable variable starting at 0.
  2. cups_sold = cups_sold + 1; reads the current value (0), adds 1, and stores the result (1) back in the jar. Notice there’s no let this time: we’re changing an existing variable, not making a new one.
  3. cups_sold += 2; is a shortcut for cups_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:

src/main.rs
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}");
}
Output
We open at 7:00.
Max cups per order: 10

How constants differ from let variables:

  1. They use const instead of let, and can never be mut.
  2. Their names are SCREAMING_SNAKE_CASE: all capitals with underscores. This makes them easy to spot.
  3. You must write their type. : u32 means “a whole number that can’t be negative”. We’ll cover types properly in the next lesson.
  4. 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.
  5. 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:

src/main.rs
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}");
}
Output
Price with oat milk: 500
Two oat lattes: 1000
Back to one: 500
  1. Line 2 creates price with the value 450.
  2. Line 3 creates a brand new variable, also called price, using the old one to calculate 500. From here on, price means the new one.
  3. The inner { } braces make a scope: a region of code where names live. Inside it, another price (1000) shadows the outer one.
  4. When the inner scope ends at }, its price disappears, and the outer price (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:

src/main.rs
fn main() {
let cups = "3";
let cups: u32 = cups.parse().unwrap();
println!("Cups after one more: {}", cups + 1);
}
Output
Cups after one more: 4
  1. The first cups is text: "3", like something a customer typed on a website.
  2. cups.parse() tries to turn the text into a number, and : u32 says which kind of number we want.
  3. .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.
  4. The new cups is a real number, so cups + 1 works.

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:

  1. A constant DAILY_MILK_TARGET set to 12 (litres), with type u32.
  2. A mutable variable milk_litres starting at 5.
  3. A delivery arrives with 8 more litres. Update milk_litres using +=.
  4. Print the current amount and the target, using {} placeholders with the names inside.
Show solution
src/main.rs
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:

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

  • let creates a variable: a name attached to a value. Variables are immutable by default.
  • Add mut when a value needs to change. Use +=, -= and friends as shortcuts.
  • const values never change, need a type, use SCREAMING_SNAKE_CASE, and can live outside functions.
  • Shadowing (let with 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

Search lessons

Type to search all lessons.