The code the Rust compiler refuses most often on day one looks very simple: make a stock variable, then take 3 away from it. In JavaScript or Python, code like that runs. In Rust it doesn't, because a variable (a named box holding a value) made with let is sealed right away. What it holds can't be replaced unless you mark it mut (short for mutable: allowed to change) from the start.
The boards at Rusdi's Pancake Stall help you remember the difference:
letis like the price list on a laminated menu: once it is printed, it never changes.let mutis like the egg stock on a whiteboard, rewritten each time an Egg Pancake sells.constis like the stall's name on the banner: painted before opening, the same everywhere.- Shadowing is like a new note with the same label, stuck over an old one: the new note is what you read now.
let: a named box
This program makes two variables, then prints them multiplied together:
fn main() {
let sweet_price = 32;
let portions = 2;
println!("Total: {}", sweet_price * portions);
}
The output is Total: 64.
let sweet_price = 32;makes a variable namedsweet_priceholding32. The=sign fills the variable with the value on its right.- Variable names are lowercase, with underscores between words (snake_case), such as
egg_stock, noteggStock. - You don't write the type (the kind of value: a whole number, text and so on). Rust guesses the type from the value: a whole number such as
32becomes ani32, one of the whole-number types. Types come in the next lesson.
Immutable by default
Immutable means it can't change. Every let variable in Rust is immutable unless you mark it with mut. The program below makes the egg stock without mut, then takes 3 away from it. Before you look at the result, guess: does this code compile and print 247?
fn main() {
let egg_stock = 250;
println!("Egg stock: {}", egg_stock);
egg_stock -= 3;
println!("Egg stock: {}", egg_stock);
}
The result is an error from the compiler:
error[E0384]: cannot assign twice to immutable variable `egg_stock`
--> src/main.rs:4:5
|
2 | let egg_stock = 250;
| --------- first assignment to `egg_stock`
3 | println!("Egg stock: {}", egg_stock);
4 | egg_stock -= 3;
| ^^^^^^^^^^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut egg_stock = 250;
| +++
egg_stock -= 3;meansegg_stock = egg_stock - 3;: take 3 away, then store the result again. That line fills the variable again. The messagecannot assign twice to immutable variablesays an immutable variable may not be filled twice.- The compile fails, so not even
Egg stock: 250prints, let alone 247. help:already shows the fix: addmuton line 2, so the binding is mutable. A binding is Rust's word for a variable: a name tied to a value.
Why is Rust built like this? When you read code, you can be sure a let variable never changes quietly on another line. What needs to change has to be marked clearly.
let mut: allowed to change
Here is the same program with mut on line 2:
fn main() {
let mut egg_stock = 250;
println!("Egg stock: {}", egg_stock);
egg_stock -= 3;
println!("Egg stock: {}", egg_stock);
}
This time the compile succeeds, and the program prints:
Egg stock: 250
Egg stock: 247
let mutmakes a box whose contents may be replaced. Replace them withoutlet:egg_stock = 247;oregg_stock -= 3;. There are also+=and*=(add or multiply, then store).- The value may change, the type may not. For example, give the stock some text:
egg_stock = "running low";. The compiler refuses witherror[E0308]: mismatched types(the types don't match) and the noteexpected integer, found `&str`.&stris the type of text: the compiler expected an integer (a whole number), but found text. - If a
mutnever changes anything, the compiler gives the warningvariable does not need to be mutable. It is only a warning: the program still runs, but you should remove themut.
Shadowing: let again with the same name
This program uses let three times with one name, and no mut:
fn main() {
let egg_stock = 250;
println!("Egg stock: {}", egg_stock);
let egg_stock = egg_stock - 3;
println!("Egg stock: {}", egg_stock);
let egg_stock = "running low";
println!("Egg stock: {}", egg_stock);
}
The program runs and prints:
Egg stock: 250
Egg stock: 247
Egg stock: running low
- Each
letmakes a new variable. The old one isn't changed, only covered, like the old note under the new one: the nameegg_stocknow points at the new variable. let egg_stock = egg_stock - 3;may read the old value (250) on the right-hand side of=, because the new variable only exists once that line is finished.- Because the variable is new, its type may differ: from a number to text. No
mutis needed at all.
const: a fixed value for the whole program
A const for the price of an Egg Pancake:
const EGG_PRICE: u32 = 38;
fn main() {
println!("Egg Pancake: {}", EGG_PRICE);
}
constis written outsidefn main, so it can be used anywhere in the program. Its name is all capitals:EGG_PRICE.- Its type is required.
u32means a whole number with no minus sign. Without a type, the compiler refuses withmissing type for `const` item(the const has no type written). - Its value must be settled at compile time, before the program runs, and it can never change. A
constcan't takemut.
mut or shadowing?
let mut |
Shadowing (let again) |
|
|---|---|---|
| The variable | stays the same one, its value is replaced | a new variable, the old one is covered |
| Changing the type | not allowed | allowed |
| How you write it | egg_stock -= 3; |
let egg_stock = egg_stock - 3; |
Use let mut for a value that keeps changing, like the stock while the stall is open. Use shadowing when a value is turned into a new form once, such as a number turned into text.
⚠️ When does the compiler refuse your variable?
- Forgetting
mut.cannot assign twice to immutable variablemeans you filled aletvariable again. Addmutto itslet, or use shadowing. mut, then changing the type.mutonly allows a new value of the same type. To change the type, useletagain.letin front of a reassignment.let number = 20;afterlet mut number = 10;doesn't change it; it makes a new variable. To change it, writenumber = 20;withoutlet.constwithout a type.const EGG_PRICE = 38;is refused. Writeconst EGG_PRICE: u32 = 38;.
TL;DR: A variable made with let is immutable (it can't change): the compiler refuses to fill it again, with cannot assign twice to immutable variable. When the compile fails, no line runs. let mut (mut: mutable, allowed to change) lets the value change (egg_stock -= 3;: take 3 away), but its type (the kind of value) stays. Shadowing, let again with the same name, makes a new variable that may have a different type and may read the old value (let number = number * 3;). A const makes a fixed value for the whole program: its name is in capitals, its type is required, and its value is settled at compile time.
⚡ let is sealed
Write:
let egg_stock = 250;
egg_stock -= 3;
Guess first: -= means take away, then store again. Does this code compile, with the stock becoming 247?
No. The compiler refuses with cannot assign twice to immutable variable: an immutable variable (one that can't change) may not be filled twice. The compile fails, so no line runs.
Meaning: A let variable is immutable by default, as if sealed: once it is filled, what it holds can't be replaced.
⚡ mut breaks the seal
Write:
let mut egg_stock = 250;
egg_stock -= 3; // 247
Meaning: mut (short for mutable: allowed to change) breaks that seal. You may replace what a let mut variable holds without another let: here from 250 to 247. The text after // is a comment, a note the compiler skips. The value may change, but the type (the kind of value) stays.
⚡ Shadowing: let again
Write:
let egg_stock = 250;
let egg_stock = egg_stock - 3;
let egg_stock = "running low";
Meaning: Each let makes a new variable with the same name, and the old one is only covered. Line 2 reads the old value (250) on the right of =, so the new variable holds 247. Because the variable is new, its type may differ, from a number to text, with no mut.
⚡ const for a fixed value
Write:
const EGG_PRICE: u32 = 38;
Meaning: A const makes a fixed value for the whole program. It is written outside fn main, and its name is in capitals. Its type is required: u32 means a whole number with no minus sign. Its value is settled at compile time and can't change.