Variables, Types & Mutability
Immutable by default, shadowing, fixed-size integers with explicit overflow behaviour, tuples and arrays.
In Rust, variables are immutable unless you write mut, every integer type states its size and sign, and conversions between types are always explicit. These defaults remove whole categories of surprises that C programmers know well.
The basics in one program
let x = 5; cannot change. let mut count = 0; can.
Shadowing: a second let input creates a new variable, here of a different type.
checked_add returns None on overflow; wrapping_add wraps around (250 + 10 = 4 in a u8); saturating_add stops at the maximum (255).
A char is 4 bytes: it holds any Unicode scalar value, such as Ω.
300 as u8 keeps the low 8 bits: 44. as never fails, so use it only when truncation is intended.
The scalar types
let count = 0; count += 1; // error: cannot assign twice to immutable variable let mut count = 0; count += 1;
Variables are immutable unless declared mut.
let total: u32 = small_u8 + big_u32; // mismatched types let total: u32 = u32::from(small_u8) + big_u32;
Rust never converts numbers implicitly. Use From/into() for lossless conversions and try_from() or as when the value might not fit.
What is the difference between shadowing and mut?
mut lets you change the value of the same variable (same type). Shadowing with a new let creates a new variable with the same name, which may have a different type; the old one is no longer reachable.
What does 200u8.checked_mul(2) return?
None, because 400 does not fit in a u8.