Variables, Data Types and Constants
The library program needs to remember things: how many books are on loan, the longest a loan may last, the title someone just searched for. Rust gives you three tools for that, and it expects you to say up front which values are allowed to change.
The rule
letis fixed,let mutcan change,constnever changes.
let binds a name to a value, immutably by default.
let on_loan = 3;
on_loan = 4; // error: cannot assign twice to immutable variablelet mut allows reassignment.
let mut on_loan = 3;
on_loan += 1; // fine, now 4const is a value fixed for the whole program. It must have a written type, and by convention its name is in capitals.
const MAX_LOAN_DAYS: u32 = 21;Every value has a type. Usually the compiler infers it: let pages = 320; becomes i32, the default integer, and let rating = 4.5; becomes f64, the default float. You can write the type yourself with a colon: let pages: u32 = 320;. Once set, a variable's type cannot change.
Shadowing is a second let with the same name. It creates a new variable, which may even have a new type:
let title = "The Salt Road";
let title = title.len(); // now a number: 13The shortcut
Ask two questions of every value: "Will it change while the program runs?" and "Is it known before the program runs?"
The maximum loan length
Never changes, known in advance:
const MAX_LOAN_DAYS: u32 = 21;
The trap is adding mut "just in case". It hides which values change and invites mistakes. The compiler even warns when a mut variable is never actually changed.
Drills
Answer fast — trust the rule.
What happens when you compile let copies = 2; copies = 3;?
Which line is a valid constant?
With no annotation, what type does let pages = 320; get?
After let title = "The Salt Road"; let title = title.len();, what is true?
Remember
letis immutable by default;let mutcan be reassigned;constneeds a type and never changes.- Ask: will it change? Known in advance? Default to plain
let. - Trap: sprinkling
muteverywhere, and confusing shadowing (new variable) with mutation (same variable).
