Variables and mutability
A variable is a name for a value. In Rust, variables are safe by default: they can't change unless you say so.
Let bindings
Use let to give a value a name. Then use the name to read the value.
let age = 30;println!("{age}"); // prints 30You must create a variable before you use it.
Immutable by default
A plain let variable can't be changed. Trying to assign a new value is error E0384.
let x = 5;x = 6; // error E0384This helps you: a value that never changes is easy to follow.
mut
Add mut when you want to change a variable.
let mut score = 0;score = 10;println!("{score}"); // prints 10mut lets you change the value, but not the type. A mut number stays a number.
Shadowing
A second let with the same name makes a brand new variable. The old one is hidden. The new one may even have a different type.
let x = 5;let x = x + 1; // a new x, equal to 6let s = " ";let s = s.len(); // now s is a number: 3Shadowing inside a { } block only lasts until the block ends.
Constants
A const is a value that never changes and is known when the program is built.
const MAX_SCORE: u32 = 100;- It always needs a type, like
: u32. - Its value can't come from a normal variable (error E0435).
- Its name is in CAPS by habit.
- You can never assign to it.
Remember
letmakes a variable; it can't change.let mutmakes a variable you can change.- E0384 means "you changed a variable that is not
mut". - A new
letwith the same name is shadowing, and it can change the type. constneeds a type and a fixed value.