Step 2 of 6
Immutable by default, and mut
In Rust, once a value is bound to a name, it can't be changed. Variables are immutable (unchangeable) by default:
fn main() {
let health = 100;
println!("health: {}", health);
health = 70;
println!("health: {}", health);
}
error[E0384]: cannot assign twice to immutable variable `health`
--> src/main.rs:4:5
|
2 | let health = 100;
| ------ first assignment to `health`
3 | println!("health: {}", health);
4 | health = 70;
| ^^^^^^^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut health = 100;
| +++
The help: lines show the fix: the keyword mut (short for mutable, changeable).
fn main() {
let mut health = 100;
println!("health: {}", health);
health = 70;
println!("health: {}", health);
}
health: 100
health: 70
health = 70;, without let, is an assignment: it puts a new value into an existing mutable variable.
Why immutable by default?
Most values in a program never change after they're set. When a variable can't change, you (and your teammates) can read let tax = 20; and trust it's still 20 a hundred lines later, without checking every line in between. When something must change, mut puts a visible marker on it. The compiler enforces both sides: it refuses assignments to immutable variables, and it warns when you write mut but never change the variable (warning: variable does not need to be mutable).
Updating a variable from its old value
The right side is worked out first, so a variable can appear on both sides of =:
fn main() {
let mut gold = 10;
gold = gold + 5;
gold += 20;
gold -= 3;
gold *= 2;
println!("gold: {}", gold);
}
gold: 64
gold += 20 is short for gold = gold + 20. These compound assignment operators exist for +, -, *, / and %. Step by step: 10 + 5 = 15, + 20 = 35, - 3 = 32, * 2 = 64.
Both forms work, but Rust code uses the short one: clippy (the linter from the Hello module) suggests gold += 5 when it sees gold = gold + 5 (its assign_op_pattern lint).
Common mistakes
- Forgetting
mut: the E0384 error above. Read thehelp:lines; rustc shows the exact fix. - Writing
letagain when you meant to change the variable:let health = 70;creates a new variable instead (the next step explains why that's allowed). To change the existing one, leave outlet. count++: Rust has no++or--operators (error: Rust has no postfix increment operator). Writecount += 1.
Your task
The program below doesn't compile. Fix it so it prints these three lines (the player takes 30 damage, then drinks a potion worth 15):
health: 100
health: 70
health: 85
Challenge 2
Fill in the operators so the step counter adds 1200 and then 800 to steps, using the short form that adds to a variable. It should print Steps today: 2000.
Challenge 3
A bank account starts with a balance of 500. Deposit 250, then withdraw 100, printing the balance at the start and after each change:
balance: 500
balance: 750
balance: 650
Use one mutable variable and the += and -= operators.