The Analogy: The Catalogue Entry That Is Not A Product
A furniture catalogue has one entry for the Halden shelving unit. The drawing is printed once, the dimensions are printed once, the assembly steps are printed once, and at the bottom of the entry there is a single line: available in oak, pine or ash. Everything about the unit that can be settled in advance has been settled in advance. The material is the one thing the entry deliberately leaves open.
The entry is not a shelving unit. You cannot stand a book on it. What arrives at your door is never "a Halden" either -- it is a Halden in oak, and it is oak all the way through: the uprights, the shelves and the pegs. There is no material switch on the finished item, no dial you turn to make it pine on Thursdays. The choice happened before anything was cut, and afterwards the object is as fixed as if the design had only ever existed in oak. That is exactly why the catalogue can promise the same dimensions for all three finishes: each one was built from the same drawing.
It also explains the thing that trips people up when ordering. The entry offers one material line, not a material line per part, so there is no way to ask for oak uprights with pine shelves. If you want that, the catalogue needs a different entry -- one with two blanks on the material line instead of one. And that is a real design decision rather than an oversight, because two blanks means every single customer now has two choices to make instead of one.
Finally, the entry is not silent about what materials will do. The assembly steps involve screws, so the material has to hold a screw; the same drawing would be nonsense for a shelving unit in sand or in water. The catalogue does not attempt to list every acceptable timber. It states a requirement and leaves the set open, and anything meeting the requirement can be built to this drawing. This lesson is about writing the entry -- the blanks, and what filling them in produces. The requirement half of the story has its own name in Rust, trait bounds, and its own lesson later in this module.
Syntax or Core Structure
A type parameter is declared in angle brackets after the name, and from that point on it is usable as a type inside the definition:
struct Pair<T> {
left: T,
right: T,
}
impl<T> Pair<T> {
fn new(left: T, right: T) -> Pair<T> {
Pair { left, right }
}
}
impl Pair<i32> {
fn sum(&self) -> i32 {
self.left + self.right
}
}
fn main() {
let numbers = Pair::new(3, 9);
let words = Pair::new("north", "south");
println!("numbers {} {} sum {}", numbers.left, numbers.right, numbers.sum());
println!("words {} {}", words.left, words.right);
}
Output:
numbers 3 9 sum 12
words north south
There are three declarations of interest here and they do different jobs. struct Pair<T> introduces the name T for use inside the struct body. impl<T> Pair<T> introduces the name a second time -- the <T> immediately after impl is the declaration, and the <T> after Pair says which instantiations this block applies to, namely all of them. Reading it as "for any T, here are methods on Pair of T" gets the shape right.
The third block, impl Pair<i32>, declares nothing and applies to exactly one instantiation. sum exists on Pair<i32> and nowhere else. Adding words.sum() to that program does not produce a bad answer; it fails to compile, because Pair<&str> has no such method. This is the catalogue's material line doing its work at the type level: the oak unit and the pine unit are different objects, and a method written for one is not on the other.
Nothing in main mentions a type. Pair::new(3, 9) produces a Pair<i32> because integer literals default to i32, and Pair::new("north", "south") produces a Pair<&str>. Inference is doing the ordering for you.
Type parameters can be declared in six places, and it is worth knowing all six by sight:
| Position | Written as | What it means |
|---|---|---|
| Struct | struct Pair<T> | The struct is a family; each T gives one member |
| Enum | enum Reading<T> | Same, and the variants may use T or ignore it |
| Blanket inherent impl | impl<T> Pair<T> | These methods exist for every instantiation |
| Concrete inherent impl | impl Pair<i32> | These methods exist for one instantiation only |
| Method | fn paired_with<U> | A parameter chosen fresh at every call |
| Free function | fn first<T> | The next lesson's subject |
Technical Depth: What The Compiler Actually Builds
Monomorphization
Rust does not compile one Pair that works for all types. For every instantiation you actually use, it stamps out a separate concrete type and a separate copy of every method you call on it. The generic definition itself is never present in the finished binary. The clearest way to see this is to ask two instantiations how big they are:
struct Wrapper<T> {
inner: T,
}
impl<T> Wrapper<T> {
fn get(&self) -> &T {
&self.inner
}
}
fn main() {
let a = Wrapper { inner: 7u8 };
let b = Wrapper { inner: [0u64; 4] };
println!("u8 {} bytes, holds {}", std::mem::size_of_val(&a), a.get());
println!("[u64;4] {} bytes, holds {} values", std::mem::size_of_val(&b), b.get().len());
}
Output:
u8 1 bytes, holds 7
[u64;4] 32 bytes, holds 4 values
One byte and thirty-two bytes. If Wrapper<T> were a single runtime thing that could hold anything, every Wrapper would have to be the same size -- big enough for the largest possibility, or a pointer to something heap-allocated. Neither happens. Wrapper<u8> is a one-byte type that the optimiser can keep in a register, and Wrapper<[u64; 4]> is thirty-two bytes laid out inline. This is the whole reason generic code in Rust is not slower than the hand-written version: after monomorphization it is the hand-written version.
The bill for this arrives in two places, and both are real. Compile times grow with the number of instantiations, not the number of definitions, so a heavily generic crate used at a dozen types compiles a dozen times over. Binary size grows the same way. The alternative -- one copy of the code, working through a pointer, deciding at runtime -- also exists in Rust and is called a trait object; it is the subject of the next two lessons, and it trades a little speed for a lot of code size.
One parameter means one type
The most common early mistake is assuming a single parameter can stand for different types in different fields. It cannot. T is one blank on the material line, filled in once:
struct Point<T, U> {
x: T,
y: U,
}
fn main() {
let both_ints = Point { x: 5, y: 4 };
let mixed = Point { x: 5, y: 4.5 };
let labelled = Point { x: "origin", y: 0 };
println!("both {} {}", both_ints.x, both_ints.y);
println!("mixed {} {}", mixed.x, mixed.y);
println!("label {} {}", labelled.x, labelled.y);
}
Output:
both 5 4
mixed 5 4.5
label origin 0
Written with a single T, the second of those three lines would not compile: x: 5 fixes T to an integer and y: 4.5 then demands it be a float, and the compiler reports a type mismatch on the float with the integer as the expected type. With two parameters all three lines are fine.
Notice what the second parameter cost, though. There are now three distinct types in play -- Point<i32, i32>, Point<i32, f64> and Point<&str, i32> -- and any function that takes a Point has to decide which of them it accepts, or become generic itself and push the decision further out. Adding a parameter is not free generosity; it moves a decision from you to every caller.
Generic enums, which you have been using for two modules
Option<T> and Result<T, E> are ordinary generic enums with no special privileges. Everything from Module 3 and Module 5 was a generic data type; it simply arrived without the vocabulary attached. Writing your own works the same way, including concrete impl blocks per instantiation:
enum Reading<T> {
Exact(T),
Range(T, T),
Missing,
}
impl Reading<u32> {
fn describe(&self) -> String {
match self {
Reading::Exact(v) => format!("exactly {v}"),
Reading::Range(low, high) => format!("between {low} and {high}"),
Reading::Missing => String::from("no reading"),
}
}
}
impl Reading<f64> {
fn midpoint(&self) -> Option<f64> {
match self {
Reading::Exact(v) => Some(*v),
Reading::Range(low, high) => Some((low + high) / 2.0),
Reading::Missing => None,
}
}
}
fn main() {
let counts = [Reading::Exact(12u32), Reading::Range(5, 9), Reading::Missing];
for r in &counts {
println!("count {}", r.describe());
}
let temps = [Reading::Exact(19.25f64), Reading::Range(18.0, 23.0), Reading::Missing];
for r in &temps {
match r.midpoint() {
Some(v) => println!("temp {v}"),
None => println!("temp no reading"),
}
}
}
Output:
count exactly 12
count between 5 and 9
count no reading
temp 19.25
temp 20.5
temp no reading
Reading<u32> gets a describe, Reading<f64> gets a midpoint, and neither has the other's method. The three variants are declared once and exist at every instantiation. This is also a preview of why the next lessons matter: describe and midpoint are the same idea at two types, and writing them separately is exactly the duplication that trait bounds remove.
A method may bring its own parameter
The parameters on an impl block are fixed when the value is created. A parameter declared on the method is chosen fresh at each call:
struct Holder<T> {
value: T,
}
impl<T> Holder<T> {
fn paired_with<U>(self, other: U) -> (T, U) {
(self.value, other)
}
}
fn main() {
let h = Holder { value: 5 };
let (a, b) = h.paired_with("five");
println!("{a} {b}");
let g = Holder { value: 'x' };
let (c, d) = g.paired_with(true);
println!("{c} {d}");
}
Output:
5 five
x true
T was decided when h was built and cannot change. U is decided at the call, which is why the same method returns (i32, &str) once and (char, bool) the next time.
Saying the type out loud
Inference covers most cases, but there are four ways to pin an instantiation and all four turn up in real code:
fn main() {
let a = "42".parse::<u32>().unwrap();
let b: u32 = "42".parse().unwrap();
let c: Vec<u8> = Vec::new();
let d = Vec::<u8>::new();
println!("{a} {b} {} {}", c.len(), d.len());
}
Output:
42 42 0 0
The ::<...> form is called the turbofish, and it exists because parse<u32>(...) would be ambiguous with a comparison. Reach for an annotation or a turbofish when inference genuinely has nothing to go on -- let v = Vec::new(); with no later use that pins the element type is an error, not a default.
| Form | Where it goes | Use it when |
|---|---|---|
| Inferred | nowhere | The usual case; something downstream fixes the type |
| Annotation on the binding | let c: Vec<u8> | The type reads better on the left |
| Turbofish on the call | "42".parse::<u32>() | Mid-chain, where there is no binding to annotate |
| Turbofish on the type | Vec::<u8>::new() | Calling an associated function with nothing else to infer from |
Real World Example: A Fixed-Size History Buffer Used By Three Subsystems
Three parts of a service each want to keep the last few of something and throw the oldest away: recent ping times, recent commands, recent temperature samples. The counting, the capacity check and the eviction rule are identical in all three. Only the thing being stored differs.
struct Sample {
minute: u32,
celsius: f64,
}
struct History<T> {
slots: Vec<T>,
limit: usize,
dropped: usize,
}
impl<T> History<T> {
fn new(limit: usize) -> History<T> {
History { slots: Vec::new(), limit, dropped: 0 }
}
fn record(&mut self, item: T) {
if self.slots.len() == self.limit {
self.slots.remove(0);
self.dropped += 1;
}
self.slots.push(item);
}
fn len(&self) -> usize {
self.slots.len()
}
fn dropped(&self) -> usize {
self.dropped
}
fn oldest(&self) -> Option<&T> {
self.slots.first()
}
fn newest(&self) -> Option<&T> {
self.slots.last()
}
}
impl History<u32> {
fn worst(&self) -> Option<u32> {
let mut best: Option<u32> = None;
for &v in &self.slots {
best = match best {
Some(b) if b >= v => Some(b),
_ => Some(v),
};
}
best
}
}
impl History<String> {
fn joined(&self) -> String {
self.slots.join(" > ")
}
}
impl History<Sample> {
fn warmest(&self) -> Option<&Sample> {
let mut best: Option<&Sample> = None;
for s in &self.slots {
best = match best {
Some(b) if b.celsius >= s.celsius => Some(b),
_ => Some(s),
};
}
best
}
}
fn main() {
let mut pings: History<u32> = History::new(4);
for ms in [31, 28, 34, 240, 29, 30] {
pings.record(ms);
}
let mut commands: History<String> = History::new(3);
for name in ["load", "verify", "apply", "report"] {
commands.record(String::from(name));
}
let mut temps: History<Sample> = History::new(3);
for (minute, celsius) in [(1u32, 19.5), (2, 21.5), (3, 20.25), (4, 22.75)] {
temps.record(Sample { minute, celsius });
}
println!("pings kept {} dropped {}", pings.len(), pings.dropped());
match (pings.oldest(), pings.newest(), pings.worst()) {
(Some(o), Some(n), Some(w)) => println!(" oldest {o} newest {n} worst {w}"),
_ => println!(" empty"),
}
println!("commands kept {} dropped {}", commands.len(), commands.dropped());
println!(" {}", commands.joined());
println!("temps kept {} dropped {}", temps.len(), temps.dropped());
match (temps.oldest(), temps.warmest()) {
(Some(o), Some(w)) => println!(
" oldest minute {} at {} warmest minute {} at {}",
o.minute, o.celsius, w.minute, w.celsius
),
_ => println!(" empty"),
}
}
Output:
pings kept 4 dropped 2
oldest 34 newest 30 worst 240
commands kept 3 dropped 1
verify > apply > report
temps kept 3 dropped 1
oldest minute 2 at 21.5 warmest minute 4 at 22.75
Look at what ended up inside impl<T> History<T> and what did not. The generic block holds the mechanism: how many slots are in use, when the buffer is full, which end is old, how many evictions have happened. None of that needs to know anything about a T beyond that it exists and can be moved. The eviction rule is written once and tested once, and the pings buffer, the command buffer and the sample buffer cannot drift apart, because there is only one copy of it to get wrong.
The three concrete blocks hold everything that does need to know the type. worst compares u32 values, joined calls a String method, warmest reaches into a field that only Sample has. Each is attached to exactly one instantiation and invisible on the other two, so pings.joined() is a compile error rather than a runtime surprise. After monomorphization there are three separate record functions in the binary: the Sample one shifts sixteen bytes per element on a 64-bit target, the u32 one shifts four, and neither pays anything for the other's existence.
The limitation of this design is worth stating plainly, because it is the reason the next three lessons exist. Without a way to state a requirement, the generic half can only do structural things -- count, move, index, hand back a reference. It cannot compare two T values, print one, or copy one. That is why worst and warmest are two separate functions doing the same job at two types, and why there is no History<T>::worst covering both. traits name capabilities and trait bounds attach them to a parameter, and with those in hand the duplication collapses into one function.
Four honest limits. remove(0) shifts every remaining element down one, so a buffer of a thousand samples does a thousand moves per insertion; the right structure is VecDeque, which the standard library provides and which makes both ends cheap. History::new(0) is broken -- the length equals the limit immediately, so the first record calls remove(0) on an empty Vec and panics on the index; nothing in the type stops a caller passing zero. dropped counts evictions rather than total records, which is a defensible choice that the name does not communicate. And the String buffer stores owned copies of every command, so a subsystem that logs long strings quietly holds three of them alive for as long as the buffer exists.
Common Mistakes
- One type parameter used for two independently varying fields.
struct Point<T> { x: T, y: T }followed byPoint { x: 5, y: 4.0 }is a type mismatch, not a clever inference. Two blanks need two parameters.
- Forgetting to declare the parameter on the impl block.
impl Pair<T>without the<T>afterimplfails with a cannot-find-type error, becauseThas never been introduced. The declaration comes before the use, every time.
- Expecting a concrete impl block's methods everywhere. A method in
impl Pair<i32>does not exist onPair<&str>. The compiler reports no method found, which is the design working rather than failing.
- Thinking the type is chosen at runtime. It is chosen at every call site, at compile time, and baked in. There is no value in a generic struct that remembers which
Tit is, becauseWrapper<u8>andWrapper<[u64; 4]>are simply different types of different sizes.
- Adding a parameter that appears exactly once in a signature. If
Tshows up in one argument and nowhere else, you probably wanted a concrete type or a trait object. A parameter earns its place by tying two positions together.
- Assuming generality is free. Every instantiation you use is another copy compiled, and a widely generic API used at fifteen types pays fifteen times in compile time and code size.
let v = Vec::new();with nothing downstream to fix the element type. This is a type-annotations-needed error, not a default to some obvious choice. Annotate the binding or turbofish the call.
- Expecting to add, compare, print or clone a
Twith no requirement stated. Insideimpl<T>,Tcan do nothing but exist and move. Every capability has to be asked for.
- Naming a parameter after a real type.
struct Cache<String>compiles and declares a parameter that happens to be spelledString, shadowing the actualStringtype inside the definition. Every error message afterwards will be about the wrong thing.
Best Practices
- Write the concrete version first and generalise on the second real use. A parameter added for one caller is a guess; one added for two is a measurement.
- Use
TandUfor slots with no role, and a real word --Item,Key,Payload-- as soon as the slot means something. The name is documentation that appears in every error message.
- Keep the mechanism in the blanket
impl<T>block and the domain knowledge in concrete impl blocks. The split is usually obvious: anything that inspects a value belongs in the concrete half until you have trait bounds.
- Give each independently varying position its own parameter, and be honest that each one is a decision handed to the caller.
- Prefer inference. Annotate the binding when the type reads better on the left, and turbofish only mid-chain where there is no binding to annotate.
- Test the generic mechanism at a single cheap instantiation. Every other instantiation runs the same code, so a second set of tests for it buys almost nothing.
- Watch the number of instantiations rather than the number of definitions when compile times start to hurt. Three definitions used at twelve types is thirty-six copies.
- Reach for a concrete type when there is only one type. Generic code with a single instantiation in the whole program is a cost with no benefit yet.
Practice Exercises
- Fix
History::new(0). Decide whether zero should be rejected, treated as one, or made to discard everything, implement your choice, and say what the caller now has to handle that it did not before.
- Add a
swapmethod toPoint<T, U>that consumes the point and returns aPoint<U, T>. Write out the impl block header first and explain which<...>in it is a declaration and which is an application.
- Add
impl History<bool>with a method counting how manytruevalues are held. Then explain, in one sentence, why this cannot be written as one method coveringHistory<bool>andHistory<u32>with the tools in this lesson.
- Give
Historya second type parameter for a label attached at construction, so aHistory<u32, &str>can carry the string"ping ms". Then say what every existing call site had to change and whether the parameter paid for itself.