The Analogy: The Pharmacist's Graduated Cylinders
Walk behind the counter of a compounding pharmacy and you will find a rack of glass cylinders. One holds 10 millilitres with marks every 0.1 ml. One holds 500 ml with marks every 5 ml. There is a separate set of vessels for solids, measured in grams, and nobody uses them interchangeably. The rack is not there to slow the pharmacist down. It is there because the size and the units of the vessel are part of the measurement, and choosing the wrong vessel is the same thing as getting the answer wrong.
Two properties of a cylinder matter before you pour anything into it. The first is capacity. A 100 ml cylinder does not "sort of" hold 500 ml; the excess ends up on the counter, and whatever number you read off the side afterwards is fiction. The second is what the graduations mean. A cylinder marked in millilitres tells you nothing about mass, and there is no honest way to read grams off it without knowing the density of what is inside. A pharmacist who ignores either property is not being efficient. They are guessing.
Rust's scalar types are that rack. u8 is the 255-capacity vessel, i32 is the default work-horse, u64 is the big one you reach for when you are counting bytes on a disk. Signedness is a graduation question: u32 has no marks below zero, so subtracting past zero is not a small number, it is an error. f64 measures a different quantity altogether -- continuous, approximate, with its own precision limits -- and Rust will not quietly pour an integer into it, or a float into an integer, because the two are not the same kind of measurement. Even char is its own vessel: four bytes wide, holding one Unicode scalar value, not one byte of text.
The payoff is that overflow becomes a visible event instead of a rumour. In a debug build, adding 10 to a u8 holding 250 stops the program and tells you where. In a release build it wraps to 4, which is defined behaviour rather than the undefined behaviour C gives you, and Rust hands you checked_add, saturating_add, and wrapping_add so you can say in the code which of those three you meant. Picking the right cylinder up front is what makes the reading trustworthy later. The rest of this lesson is the tour of the rack.
Syntax or Core Structure
Every type below is either a scalar (one value: integer, float, bool, char) or a compound (several values gathered into one: tuple, array). Annotations are optional wherever inference can reach the answer, and mandatory where it cannot.
fn main() {
// Integers: the width and the signedness are part of the type.
let small: i8 = -128;
let big: u64 = 18_446_744_073_709_551_615;
let inferred = 42; // no annotation -> i32 by default
let index: usize = 3;
// Floats: f64 by default, f32 when you ask for it.
let ratio = 2.5; // f64
let single: f32 = 2.5;
// Booleans and characters. A char is a Unicode scalar value, not a byte.
let ready: bool = true;
let grade: char = 'A';
// Tuple: fixed length, types may differ, fields reached by position.
let point: (i32, i32, &str) = (3, -7, "origin offset");
let (x, y, label) = point;
// Array: fixed length, every element the same type.
let weeks: [u8; 4] = [7, 14, 21, 28];
let zeros = [0u16; 3]; // three copies of 0
println!("small = {small}, big = {big}");
println!("inferred = {inferred}, index = {index}");
println!("ratio = {ratio}, single = {single}");
println!("ready = {ready}, grade = {grade}");
println!("point = {:?}", point);
println!("x = {x}, y = {y}, label = {label}");
println!("point.2 = {}", point.2);
println!("weeks = {:?}, len = {}", weeks, weeks.len());
println!("weeks[1] = {}", weeks[1]);
println!("zeros = {:?}", zeros);
}
Output:
small = -128, big = 18446744073709551615
inferred = 42, index = 3
ratio = 2.5, single = 2.5
ready = true, grade = A
point = (3, -7, "origin offset")
x = 3, y = -7, label = origin offset
point.2 = origin offset
weeks = [7, 14, 21, 28], len = 4
weeks[1] = 14
zeros = [0, 0, 0]
Three details in that output are worth pausing on. {:?} (the Debug format) puts quotes around the &str inside the tuple while {} (the Display format) does not, which is exactly the difference between "show me this for a log" and "show me this for a user". point is still usable after let (x, y, label) = point; because every field is Copy, so destructuring copied rather than moved. And weeks.len() returns 4 without touching memory at run time -- the length lives in the type [u8; 4], so the compiler already knows it.
Technical Depth: Widths, Wrapping, and Conversions
The integer rack
| Type | Bits | Range |
|---|---|---|
i8 / u8 | 8 | -128 .. 127 / 0 .. 255 |
i16 / u16 | 16 | -32,768 .. 32,767 / 0 .. 65,535 |
i32 / u32 | 32 | -2,147,483,648 .. 2,147,483,647 / 0 .. 4,294,967,295 |
i64 / u64 | 64 | about -9.22e18 .. 9.22e18 / 0 .. 18,446,744,073,709,551,615 |
i128 / u128 | 128 | about -1.7e38 .. 1.7e38 / 0 .. 3.4e38 |
isize / usize | pointer-sized | 64 bits on a 64-bit target, 32 on a 32-bit target |
i32 is the inference default because it is the fastest integer on essentially every modern target and wide enough for ordinary counting. usize is the type of every length and every index in the standard library, which is why Vec::len returns usize and why indexing with an i32 is a compile error rather than a silent conversion.
Every one of these types carries its own bounds as associated constants, so you never have to remember the table:
println!("{} {} {}", i8::MIN, i8::MAX, u32::MAX);
println!("{} {}", usize::BITS, std::mem::size_of::<char>());
Floats, bools, chars
| Type | Size | What it holds |
|---|---|---|
f32 | 4 bytes | IEEE-754 single precision, about 7 significant decimal digits |
f64 | 8 bytes | IEEE-754 double precision, about 15 significant decimal digits |
bool | 1 byte | true or false, never an integer |
char | 4 bytes | one Unicode scalar value, U+0000..U+D7FF and U+E000..U+10FFFF |
() | 0 bytes | the unit type: "no value", what a function returns by default |
f64 is the float default for the same reason i32 is the integer default: on current hardware it is not meaningfully slower than f32 and it stops you losing digits by accident. Note that bool is genuinely not a number -- if 1 does not compile, and true + 1 does not either. If you want the integer, write ready as u8 or u8::from(ready).
The char size surprises people. It is four bytes because it stores a code point, not a UTF-8 byte, which means std::mem::size_of::<char>() is 4 while "e".len() is 1 and "\u{00e9}".len() is 2. String indexing is covered properly in the Mastering Strings lesson; the rule to carry from here is that len() on a string counts bytes.
Overflow is a decision, not an accident
In a debug build, an arithmetic overflow panics with attempt to add with overflow and a line number. In a release build the same expression wraps using two's complement. Both behaviours are defined -- unlike C, Rust never calls this undefined behaviour -- but they differ, so an overflow that only your release build reaches is a real class of bug. The fix is to say what you meant:
| Family | Returns | Use when |
|---|---|---|
checked_add | Option<T>, None on overflow | overflow is an error you want to handle |
saturating_add | T, clamped to MIN/MAX | a counter or gauge that should peg, not wrap |
wrapping_add | T, wrapped | hashes, checksums, ring buffers -- wrapping is the intent |
overflowing_add | (T, bool) | you want the wrapped value and to know it happened |
checked_ and wrapping_ exist for every arithmetic operation -- add, sub, mul, div, rem, neg, pow, and the shifts -- while saturating_ and overflowing_ cover the ones where clamping or a carry flag is meaningful. There is also overflow-checks = true, which you can set on the release profile when a panic is preferable to a wrong number in production.
as truncates in silence; try_from tells you
as is a cast, not a conversion, and it never fails and never complains. That makes it the right tool for lossless widening (u32 to u64) and the wrong tool for everything else.
fn main() {
let a: u8 = 250;
println!("wrapping_add(10) = {}", a.wrapping_add(10));
println!("checked_add(10) = {:?}", a.checked_add(10));
println!("checked_add(5) = {:?}", a.checked_add(5));
println!("saturating_add(10) = {}", a.saturating_add(10));
println!("overflowing_add(10) = {:?}", a.overflowing_add(10));
let n: i32 = 300;
println!("300i32 as u8 = {}", n as u8);
println!("-1i32 as u8 = {}", -1i32 as u8);
println!("3.9f64 as i32 = {}", 3.9f64 as i32);
println!("-3.9f64 as i32 = {}", -3.9f64 as i32);
println!("300.0f64 as u8 = {}", 300.0f64 as u8);
println!("0.1 + 0.2 = {}", 0.1f64 + 0.2);
println!("equal to 0.3? = {}", 0.1f64 + 0.2 == 0.3);
println!("try_from(300) = {:?}", u8::try_from(300i32));
println!("try_from(200) = {:?}", u8::try_from(200i32));
}
Output:
wrapping_add(10) = 4
checked_add(10) = None
checked_add(5) = Some(255)
saturating_add(10) = 255
overflowing_add(10) = (4, true)
300i32 as u8 = 44
-1i32 as u8 = 255
3.9f64 as i32 = 3
-3.9f64 as i32 = -3
300.0f64 as u8 = 255
0.1 + 0.2 = 0.30000000000000004
equal to 0.3? = false
try_from(300) = Err(TryFromIntError(()))
try_from(200) = Ok(200)
Read that block as a list of traps. 300 as u8 keeps the low eight bits and gives 44. -1 as u8 reinterprets the bit pattern and gives 255. Float-to-integer casts truncate toward zero rather than rounding, so both 3.9 and -3.9 lose their fraction; since Rust 1.45 they also saturate, so 300.0 as u8 is 255 and f64::NAN as i32 is 0 instead of the garbage older versions produced. And 0.1 + 0.2 is not 0.3 in binary floating point, in Rust exactly as in every other IEEE-754 language -- clippy will flag that == for you under clippy::float_cmp.
Inference, literals, and where annotations become mandatory
| Situation | What Rust does |
|---|---|
let n = 42; | defaults to i32 |
let x = 2.5; | defaults to f64 |
let n = 42u8; or let n: u8 = 42; | suffix or annotation wins over the default |
let v = Vec::new(); then v.push(1u8) | infers Vec<u8> from the later use |
"7".parse() with no target type | error[E0284]: type annotations needed |
const / static items | annotation always required |
Literals accept _ anywhere as a visual separator, and 0x, 0o, 0b prefixes for hex, octal, and binary. b'A' is a u8 byte literal equal to 65. A literal too large for its annotated type is caught at compile time by the overflowing_literals lint -- let x: u8 = 300; is an error, not a wrap.
Real World Example: Budgeting Bytes for an Upload Queue
An upload service splits every file into fixed-size chunks, groups chunks into jobs, and reports the queue back to an operator. Nothing here is exotic, and yet almost every type decision in the lesson shows up: byte counts want u64, chunk counts want ceiling division, percentages want f64, and the retry budget has to cross a width boundary safely.
const CHUNK_BYTES: u64 = 64 * 1024; // 65_536
const MAX_CHUNKS_PER_JOB: u32 = 8;
/// Ceiling division without the classic (a + b - 1) / b overflow hazard.
fn chunks_for(size_bytes: u64) -> u64 {
size_bytes.div_ceil(CHUNK_BYTES)
}
fn human(size_bytes: u64) -> String {
const KIB: f64 = 1024.0;
let b = size_bytes as f64;
if b < KIB {
format!("{size_bytes} B")
} else if b < KIB * KIB {
format!("{:.1} KiB", b / KIB)
} else {
format!("{:.2} MiB", b / (KIB * KIB))
}
}
fn main() {
// (&str, u64) is Copy, so this array is Copy and survives the loop below.
let files: [(&str, u64); 4] = [
("logo.png", 12_400),
("report.pdf", 2_500_000),
("clip.mp4", 734_003_200),
("empty.txt", 0),
];
let mut total_bytes: u64 = 0;
let mut total_chunks: u64 = 0;
println!("{:<12} {:>12} {:>8} {:>6}", "file", "size", "chunks", "jobs");
for (name, size) in files {
let chunks = chunks_for(size);
// u32 -> u64 is lossless, so `as` is honest here.
let jobs = chunks.div_ceil(MAX_CHUNKS_PER_JOB as u64);
total_bytes += size;
total_chunks += chunks;
println!("{:<12} {:>12} {:>8} {:>6}", name, human(size), chunks, jobs);
}
println!();
println!("total = {}", human(total_bytes));
println!("total chunks = {total_chunks}");
let biggest = files.iter().map(|(_, s)| *s).max().unwrap_or(0);
let share = biggest as f64 / total_bytes as f64 * 100.0;
println!("largest file is {:.1}% of the queue", share);
let daily = total_chunks * 3 * 24; // 3 retries, 24 runs per day
println!("daily chunk uploads = {daily}");
println!("fits in u32? {}", u32::try_from(daily).is_ok());
println!("fits in u16? {}", u16::try_from(daily).is_ok());
println!("daily as u16 (silent truncation) = {}", daily as u16);
}
Output:
file size chunks jobs
logo.png 12.1 KiB 1 1
report.pdf 2.38 MiB 39 5
clip.mp4 700.00 MiB 11200 1400
empty.txt 0 B 0 0
total = 702.40 MiB
total chunks = 11240
largest file is 99.7% of the queue
daily chunk uploads = 809280
fits in u32? true
fits in u16? false
daily as u16 (silent truncation) = 22848
The last four lines are the whole argument for taking widths seriously. 809280 is a perfectly ordinary number; it fits in a u32 with room to spare and does not fit in a u16 at all. u32::try_from and u16::try_from answer that question honestly, returning Ok and Err respectively, while daily as u16 answers it by throwing away the high bits and handing back 22848 -- a number that looks like a plausible upload count and understates the real one by exactly 786,432, which is 12 x 65,536. Nothing warns you. That is why as belongs on widening conversions and try_from belongs everywhere else.
chunks_for is deliberately written with div_ceil rather than the idiom most people reach for first. (size_bytes + CHUNK_BYTES - 1) / CHUNK_BYTES gives the same answer for every input in this example, and panics in a debug build for any size_bytes within 65,535 of u64::MAX, because the addition overflows before the division can happen. div_ceil (stable since Rust 1.73) has no intermediate value to overflow. When a standard-library method exists for the arithmetic you are hand-rolling, it usually exists because the hand-rolled version has an edge case.
human is the one place where the float is the right choice. Byte counts must stay integral -- you cannot have 0.4 of a byte, and accumulating total_bytes in an f64 would start losing whole bytes above 2^53 -- but the presentation is approximate by design, so casting to f64 at the last moment and formatting with {:.2} is exactly right. Note that clip.mp4 prints 700.00 MiB because 734,003,200 really is 700 x 1024 x 1024; the trailing zeros are the format specifier being consistent, not a rounding artefact.
The tuple array earns a comment because it demonstrates something easy to miss. for (name, size) in files iterates the array by value (the behaviour since edition 2021), which would normally move it -- but (&str, u64) is Copy, so arrays of it are Copy too, and files is still there for the files.iter() call afterwards. Change that u64 to a String and the same loop moves the array, and the later files.iter() stops compiling. The type decides, and the type is visible in the annotation.
Common Mistakes
- Assuming overflow behaves the same in both profiles. Debug panics, release wraps. Code that passed every test can produce a wrong number in production, so decide explicitly with
checked_/saturating_/wrapping_, or turnoverflow-checkson for release. - Using
asto change integer width.300i32 as u8is44and no diagnostic is emitted. Useu8::try_from(n)?when the value might not fit, and reserveasfor widening. - Expecting a float-to-integer cast to round.
3.9 as i32is3and-3.9 as i32is-3; casts truncate toward zero. Call.round(),.floor(), or.ceil()first if you meant something else. - Comparing floats with
==.0.1 + 0.2 == 0.3isfalse. Compare against a tolerance, or use integers -- money in particular belongs in the smallest currency unit as an integer, never inf64. - Treating
charas a byte.charis four bytes wide and holds a code point;String::len()counts UTF-8 bytes, not characters. Indexing aStringby integer does not compile at all. - Serialising a
usize. It is 8 bytes on a 64-bit target and 4 on a 32-bit one, so writing one to a file or a socket makes the format target-dependent. Picku32oru64explicitly at the boundary. - Hand-rolling ceiling division as
(a + b - 1) / b. It overflows foranearT::MAX.a.div_ceil(b)cannot. - Forgetting that the array length is part of the type.
[u8; 3]and[u8; 4]are different types, so a function taking[u8; 4]will not accept a three-element array. Take&[u8]when the length should be free. - Choosing
f32to save memory in an accumulation loop. Seven significant digits run out fast: summing thousands of values inf32visibly drifts from the same sum inf64, and the memory you saved was four bytes per value.
Best Practices
- Let the defaults stand unless you have a reason.
i32andf64are the right answer most of the time; a deliberateu8orf32should be explainable in one sentence. - Use
usizefor lengths and indices, and a fixed width for anything that crosses a boundary. In-memory sizes areusize; bytes on a wire, in a file, or in a database column areu32/u64. - Prefer
try_fromandintooveras.intofor conversions that cannot fail,try_fromfor the ones that can,asonly for lossless widening or a truncation you have commented. - Put the unit in the name.
timeout_secs,size_bytes,price_cents. The type gives you the width; the name has to give you the meaning. - Handle overflow at the edges, not everywhere. Parsing input, multiplying user-supplied quantities, and accumulating counters over long uptimes are the three places worth an explicit
checked_call. - Use
_separators and literal suffixes on anything long.18_446_744_073_709_551_615and0b1010_0001are readable; the same digits unbroken are not. - Reach for the associated constants instead of remembering ranges.
u32::MAX,i64::MIN,f64::EPSILON, andusize::BITSare always correct and always in scope. - Let
cargo clippyreferee the numeric code.float_cmp,cast_possible_truncation,cast_precision_loss, andmanual_div_ceilall catch exactly the mistakes above, and each one explains the idiom it wants instead.
Practice Exercises
- Print the rack. Write a program that prints a formatted table of
MINandMAXfori8,u8,i32,u32,i64, andu64using the associated constants and{:>24}alignment. Add a final line printingusize::BITSand explain what it tells you about the machine you ran it on. - Run the overflow lab. Start from
let n: u8 = 255;and produce the result ofn + 1,n.wrapping_add(1),n.checked_add(1), andn.saturating_add(1). Run the program withcargo runand then withcargo run --release, and write down which single line behaves differently and why. - Audit the casts. For each of
1000i32 as u8,-5i32 as u32,2.99f64 as u8,-1.5f64 as u8, andf64::INFINITY as u8, write your prediction as a comment, then print the real value. Replace each one with atry_fromor around()call that makes the intent explicit. - Free the length. Write
fn checksum(bytes: [u8; 4]) -> u32that sums its elements withwrapping_add, then try to call it with a three-element and a five-element array and record both errors. Change the signature to accept&[u8], confirm all three calls now work, and explain in one sentence what you gave up by doing so.