Integers, Floats, Booleans and Characters
A book record in the library holds a page count, a star rating, whether it is out on loan, and a shelf letter. Each of those is a scalar: a single value. Rust makes you choose a precise type for each, and then holds you to it.
The rule
Sized numbers, true or false, one Unicode char, and no silent conversions.
Integers are named by sign and bit width: i8 i16 i32 i64 i128 (signed) and u8 u16 u32 u64 u128 (unsigned, never negative). isize and usize match the machine's pointer size; usize is the type for indexes and lengths. The default is i32.
let pages: u32 = 412;
let year: i32 = -350; // signed, so negative is allowed
let big = 1_000_000; // underscores just help readingA u8 holds 0 to 255. Going past the limit is overflow: a debug build panics, a release build wraps around. When wrapping is what you want, say so with methods like wrapping_add, or use checked_add, which returns nothing on overflow.
Floats are f64 (default) and f32. let rating = 4.5; is an f64.
Booleans are bool: true or false.
Characters are char, written in single quotes. A char is four bytes and holds any Unicode scalar value, not just ASCII:
let shelf = 'F';
let mark = '✓';No silent conversions. u32 + f64 does not compile. Convert on purpose with as:
let per_page = rating / pages as f64;The shortcut
Pick a type by asking three questions in order: Can it be negative? Can it have a fraction? How big can it get?
Negative?
A count of loans can never be below zero, so unsigned: a
utype.
The trap is mixing types in one expression and expecting Rust to promote one side, as C or Python would. It will not; convert explicitly.
Drills
Answer fast — trust the rule.
What is the largest value a u8 can hold?
What type does let rating = 4.5; get with no annotation?
Which line is a valid char?
With pages: u32 and rating: f64, what happens to pages + rating?
In a debug build, what happens when a u8 holding 255 has 1 added with +?
Remember
- Integers are sized and signed or unsigned; defaults are
i32andf64;charis one Unicode value in single quotes. - Ask: negative? fraction? how big?
- Trap: no automatic conversion between numeric types; use
as.
