Variables, Data Types and Constants
A Rust variable is immutable unless marked mut, every value has a type the compiler knows, and a const is a fixed, typed value that never changes.
Choose mutable bindings, immutable bindings and compile-time constants deliberately.
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: 13