The Analogy: The Height Bar At The Gate
The ride does not keep a list of who may board. It keeps a bar. The sign says what the bar tests -- a minimum height -- and anyone who clears it boards, including thousands of people the operator will never meet. The requirement is written once, in terms of a property rather than a set of names, and it settles every future case without being revisited.
What makes the bar work is where it stands: at the gate, before anyone is strapped in. A rule enforced halfway round the loop is not a rule, it is an accident report. Trait bounds are positioned the same way. The requirement is checked where the generic code is compiled and again where each call is written, so a type that cannot do what the body needs is turned away before the program runs, not in the middle of a customer's transaction.
Real rides test more than one thing. Tall enough, under the weight limit, no recent back injury -- the sign lists them together and boarding requires all of them at once. When the list outgrows the sign it moves to a notice board beside the queue. It is the same list, differently placed, and nobody pretends the two arrangements mean different things.
And a bar set too high costs the operator business. If the harness only ever needed the rider to reach the shoulder straps, a bar set at adult height turns away children the ride could safely have carried. Every requirement you add narrows what your code will accept, permanently and for all callers. So the discipline runs in one direction: ask for exactly what the body uses, and nothing more.
Syntax or Core Structure
The previous module walked into a wall. largest could not compare two values of type T, because nothing had said T was comparable. The bound says it:
fn largest<T: PartialOrd>(items: &[T]) -> Option<&T> {
let mut best = items.first()?;
for item in items {
if item > best {
best = item;
}
}
Some(best)
}
fn main() {
let numbers = [34, 240, 29, 30];
let words = ["north", "south", "east"];
let empty: [u8; 0] = [];
println!("numbers {:?}", largest(&numbers));
println!("words {:?}", largest(&words));
println!("empty {:?}", largest(&empty));
}
Output:
numbers Some(240)
words Some("south")
empty None
The change is four characters. <T: PartialOrd> reads "for any type T that can be compared", and it does two jobs at once. Inside the body it grants permission: item > best is now a call to a method the bound guarantees exists. At every call site it imposes a condition: largest may only be handed slices whose element type has satisfied PartialOrd. Both halves are checked by the compiler, and neither costs anything at run time.
A bound can be written in several places, and the choice is about readability rather than meaning:
| Form | Written | When to reach for it |
|---|---|---|
| Inline on the parameter | fn f<T: Display>(x: T) | One or two bounds, short names |
A where clause | fn f<T>(x: T) where T: Display | Long lists, or several parameters |
On an impl block | impl<T: Display> Pair<T> | The methods inside exist only for those T |
| Argument position | fn f(x: impl Display) | A one-off parameter with no need to name its type |
| Return position | fn f() -> impl Display | The body picks one concrete type the caller need not know |
Several bounds are joined with +, and all of them must hold:
use std::fmt::Debug;
fn ranked<T: PartialOrd + Debug>(a: T, b: T) {
let (first, second) = if a > b { (a, b) } else { (b, a) };
println!("{:?} then {:?}", first, second);
}
fn main() {
ranked(3, 9);
ranked("kilo", "alpha");
ranked(2.5, 2.5);
}
Output:
9 then 3
"kilo" then "alpha"
2.5 then 2.5
PartialOrd supplies the >, Debug supplies the {:?}, and the function needs both. Drop either one from the bound and the corresponding line stops compiling -- which is a useful way to check whether a bound is really being used.
Technical Depth: Where Bounds Go And What They Cost
Methods that exist only for some type arguments
A bound on an impl block decides which methods a given instantiation has. The struct is still generic over every type; the method set is not.
use std::fmt::Display;
struct Pair<T> {
left: T,
right: T,
}
impl<T> Pair<T> {
fn new(left: T, right: T) -> Pair<T> {
Pair { left, right }
}
}
impl<T: Display> Pair<T> {
fn line(&self) -> String {
format!("{} / {}", self.left, self.right)
}
}
impl<T: Display + PartialOrd> Pair<T> {
fn larger(&self) -> &T {
if self.left > self.right {
&self.left
} else {
&self.right
}
}
}
struct Opaque;
fn main() {
let n = Pair::new(3, 9);
let w = Pair::new(String::from("north"), String::from("south"));
let _o = Pair::new(Opaque, Opaque);
println!("n {}", n.line());
println!("n max {}", n.larger());
println!("w {}", w.line());
println!("w max {}", w.larger());
println!("o built, and that is all it can do");
}
Output:
n 3 / 9
n max 9
w north / south
w max south
o built, and that is all it can do
Pair<Opaque> is a perfectly legal type: new lives in the unbounded block, so it can be constructed. It simply has no line and no larger, and calling either is a compile error naming the unsatisfied bound. That is what makes bounds on impl blocks the right home for them -- had struct Pair<T: Display> been written instead, Pair<Opaque> could not exist at all, and every function mentioning Pair<T> anywhere in the program would have had to repeat the bound.
The underscore in _o is doing real work: the value is deliberately never used, and the leading underscore is how you say so without a warning.
Static dispatch and dynamic dispatch, side by side
Module 6's third lesson left this trade open. Here are the two forms answering the same question:
use std::fmt::Display;
fn show_static<T: Display>(item: T) -> String {
format!("<{}>", item)
}
fn show_dyn(item: &dyn Display) -> String {
format!("<{}>", item)
}
fn main() {
println!("{}", show_static(7));
println!("{}", show_static("seven"));
println!("{}", show_dyn(&7));
println!("{}", show_dyn(&"seven"));
let one = 1;
let two = String::from("two");
let three = 3.5;
let mixed: Vec<&dyn Display> = vec![&one, &two, &three];
let mut out = String::new();
for item in &mixed {
out.push_str(&format!("{} ", item));
}
println!("mixed {}", out.trim());
}
Output:
<7>
<seven>
<7>
<seven>
mixed 1 two 3.5
The four <...> lines are identical, which is the point: for a single call the two forms are interchangeable. The mixed vector is where they part company. Vec<T> holds one type; there is no T that is simultaneously i32, String and f64. Vec<&dyn Display> holds three different types because each element carries its own pointer to its own fmt implementation.
Bound, e.g. T: Display | Trait object, &dyn Display | |
|---|---|---|
| Dispatch | Decided at compile time | Looked up in a vtable at run time |
| Machine code | One copy per concrete type used | One copy in total |
| Inlining across the call | Possible | Effectively blocked |
| A collection of several types | No, one T per call | Yes, that is the whole purpose |
| Needs object safety | No | Yes |
| Size of the reference | One word | Two words |
The default is the bound. Reach for dyn when a single collection or a single struct field genuinely has to hold values of types chosen elsewhere, or when the number of instantiations is measurably hurting compile time or binary size -- and measure before believing the second reason.
where clauses
A where clause moves the same requirements below the signature, which keeps the parameter list readable once there is more than one type involved:
use std::fmt::Debug;
fn audit<K, V>(label: &str, pairs: &[(K, V)])
where
K: Debug + PartialOrd,
V: Debug,
{
let mut highest: Option<&K> = None;
for (k, _) in pairs {
highest = match highest {
Some(h) if h > k => Some(h),
_ => Some(k),
};
}
println!("{label} {} pairs, highest key {:?}", pairs.len(), highest);
for (k, v) in pairs {
println!(" {:?} -> {:?}", k, v);
}
}
fn main() {
audit("ports", &[(443, "https"), (22, "ssh"), (80, "http")]);
audit("flags", &[("verbose", true), ("dry-run", false)]);
}
Output:
ports 3 pairs, highest key Some(443)
443 -> "https"
22 -> "ssh"
80 -> "http"
flags 2 pairs, highest key Some("verbose")
"verbose" -> true
"dry-run" -> false
There is one thing a where clause can express that an inline list cannot: a bound whose subject is a constructed type rather than a bare parameter, such as where Option<T>: Debug or where Vec<T>: Clone. Inline bounds attach to a parameter name, so they have nowhere to put the Option part.
impl Trait in return position
The other direction hides a type instead of demanding one:
use std::fmt::Display;
fn label(kind: &str, n: u32) -> impl Display {
format!("{kind}-{n:03}")
}
fn main() {
let a = label("valve", 7);
println!("{}", a);
println!("{}", label("pump", 142));
}
Output:
valve-007
pump-142
The caller knows only that the result can be printed. The body chose String, and could later switch to something else without breaking any caller that keeps to the promise. The restriction is that there is still exactly one concrete type: every return in the body must produce the same one, so a function returning a String on one branch and a u32 on another cannot be written this way. That case needs a trait object on the heap, which arrives in Module 8.
Real World Example: Summarising Any Measured Series
Every system accumulates series of numbers -- request latencies, sensor readings, refund amounts. The questions asked of them are identical: what is the lowest, what is the highest, how many exceeded the limit. Bounds let that be written once, and the payoff includes a type defined in the previous lesson that this code has never heard of.
use std::fmt;
#[derive(Clone, Copy, PartialEq, PartialOrd)]
struct Pence(i64);
impl fmt::Display for Pence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = format!("{}.{:02}", self.0 / 100, self.0 % 100);
f.pad(&text)
}
}
struct Series<T> {
name: &'static str,
values: Vec<T>,
}
impl<T: Copy + PartialOrd> Series<T> {
fn lowest(&self) -> Option<T> {
let mut best: Option<T> = None;
for v in &self.values {
best = match best {
Some(b) if b <= *v => Some(b),
_ => Some(*v),
};
}
best
}
fn highest(&self) -> Option<T> {
let mut best: Option<T> = None;
for v in &self.values {
best = match best {
Some(b) if b >= *v => Some(b),
_ => Some(*v),
};
}
best
}
fn above(&self, limit: T) -> usize {
let mut n = 0;
for v in &self.values {
if *v > limit {
n += 1;
}
}
n
}
}
impl<T: Copy + PartialOrd + fmt::Display> Series<T> {
fn report(&self, limit: T) -> String {
let range = match (self.lowest(), self.highest()) {
(Some(lo), Some(hi)) => format!("{lo} to {hi}"),
_ => String::from("-- to --"),
};
format!(
"{:<8} {:>3} values, {}, {} over {}",
self.name,
self.values.len(),
range,
self.above(limit),
limit
)
}
}
fn main() {
let latency = Series {
name: "latency",
values: vec![34u32, 240, 29, 30, 51],
};
let temps = Series {
name: "temps",
values: vec![19.25f64, 21.5, 20.5, 22.75],
};
let refunds = Series {
name: "refunds",
values: vec![Pence(1250), Pence(899), Pence(120050), Pence(4)],
};
let quiet: Series<u32> = Series {
name: "quiet",
values: Vec::new(),
};
println!("{}", latency.report(100));
println!("{}", temps.report(21.4));
println!("{}", refunds.report(Pence(1000)));
println!("{}", quiet.report(1));
}
Output:
latency 5 values, 29 to 240, 1 over 100
temps 4 values, 19.25 to 22.75, 2 over 21.4
refunds 4 values, 0.04 to 1200.50, 2 over 10.00
quiet 0 values, -- to --, 0 over 1
Compare this with the History buffer from the first lesson of this module. That type needed a separate impl History<u32> to find a worst value and a separate impl History<String> to join lines, because with a bare T there was no way to say "comparable" or "printable". Series needs neither. One lowest, one highest, one above and one report cover three unrelated element types, and adding a fourth costs nothing at all.
Pence is the interesting case, because Series does not know it exists and was not adjusted to admit it. It works for exactly one reason: the previous lesson gave it Display, Copy and PartialOrd, which happen to be the three capabilities report asks for. The consumer states requirements, the type satisfies them, and neither side names the other. Note also that the derived PartialOrd is trustworthy here in a way the derive on Timestamp was not: there is one field and it is the amount, so field order cannot be wrong.
The split into two impl blocks is deliberate. lowest, highest and above never print anything, so they do not ask for Display, and a Series of some unprintable type can still be searched. Pushing those bounds up onto struct Series<T> would have been the easy move and the wrong one: it would force every function anywhere in the program that so much as mentions Series<T> to repeat all three bounds, and it would make an unprintable series impossible to construct even where nobody ever wanted to print it.
Now the limits. report walks the values three times -- once in lowest, once in highest, once in above -- where one pass could do all three, and on a large series that is three times the memory traffic for no benefit. The bound is PartialOrd rather than Ord because f64 only has PartialOrd, and the consequence is real: a NAN in a temperature series compares false against everything, so which value ends up reported as lowest depends on where the NAN sits in the vector. This Pence is the simplified version without the sign branch, so a negative amount prints as -3.-5; the previous lesson's implementation handled that and this one silently does not. And the report carries no units at all, so 2 over 21.4 gives no hint whether that is degrees, seconds or pounds.
Common Mistakes
- Using a capability inside a generic body without asking for it.
item > bestwith a bareTfails withE0369, and a method call fails withE0599saying the method exists but the bound is not satisfied. Both errors end with aconsider restricting the type parameternote that contains the exact text to add. Read it rather than guessing -- it names the trait the operation actually needs, which is often narrower than the one you would have picked.
- Over-constraining out of habit. Writing
<T: Clone + Debug + Display + PartialOrd>when the body only prints turns away every caller whose type is printable but not cloneable, forever, and the compiler will never tell you because nothing is wrong. Delete a bound and recompile: if it still builds, the bound was decoration.
- Putting the bounds on the struct instead of the impl block.
struct Series<T: Display>forces the bound into every signature that mentions the type and forbids constructing a series of anything unprintable. Leave the struct generic and bound theimplblocks that need it.
- Expecting one
Tto hold several types. A bound picks one concrete type per call, soVec<T>is homogeneous no matter how permissive the bound is. A collection whose elements are genuinely of different types needsVec<Box<dyn Trait>>orVec<&dyn Trait>, and that is a different design, not a syntax variation.
- Returning
impl Traitfrom a function with two different concrete return types.if x { String::from("a") } else { 7 }behind-> impl Displayis rejected:impl Traitmeans one hidden type, not any type. Either unify the branches or return a boxed trait object.
- Treating
impl Traitin argument position as identical to a named parameter. It is an anonymous type parameter, which means callers cannot use a turbofish to pin it, and twoimpl Displayarguments are two independent types -- there is no way to say "both arguments must be the same type" without naming aT.
- Reaching for
dynfirst. Trait objects look tidier in a signature and they cost a pointer indirection on every call plus the loss of inlining. Use a bound unless you specifically need one collection or one field to hold several types.
- Asking for
PartialOrdwhereOrdis required..sort(),.max()andBTreeMapkeys all need the total ordering, andPartialOrdwill not satisfy them. Conversely floats have onlyPartialOrd, so a bound ofOrdquietly excludesf32andf64.
- Adding
T: Copyto make a borrow error go away. It usually works, and it permanently restricts the function to types that are cheap to duplicate -- excludingString,Vecand most structs. The borrow error was the real problem; take a reference or clone explicitly instead.
Best Practices
- Ask for the minimum the body actually uses. Write the function first, add bounds only when the compiler demands them, then try removing each one to confirm it is still needed.
- Keep bounds on
implblocks rather than on the struct or enum, so the type stays constructible and the bound is stated once where it is used.
- Move to a
whereclause as soon as there is more than one type parameter or more than two bounds on any of them. The signature stays scannable and the requirements read as a list.
- Default to static dispatch and switch to
dyndeliberately, for a stated reason: a heterogeneous collection, a plugin boundary, or a measured monomorphization cost.
- Group the methods that need a capability into their own
implblock, so a reader can see at a glance which bounds unlock which methods.
- Prefer
Ordfor anything that will be sorted or used as a map key, and remember that choosing it excludes floats -- which is often the correct trade for money and identifiers.
- Use
impl Traitin argument position for a genuinely one-off parameter, and a namedTwhen two arguments must share a type or a caller might want to specify it.
- When a bound list starts to look like a specification of its own, define a trait that requires the others and bound on that instead. One name in the signature beats five, and the trait can be documented.
Practice Exercises
- Add a
spanmethod toSeriesreturningOption<T>, the highest value minus the lowest. Work out which bound this needs fromstd::opsand write it as awhereclause -- the subtraction returns a type, and you must say that the type it returns isT. Then explain whyspancannot go in the sameimplblock asabove.
- Remove
Copyfrom the bounds onSeriesand makelowestandhighestreturnOption<&T>instead. Check that the code still works foru32,f64andPence, then add aSeries<String>and report its range -- something theCopyversion could never have done.
- Try to put the four series into one
Vecso a single loop can print all four reports. Establish precisely why noVec<Series<T>>and noVec<&dyn ...>of the current design can work, then define the smallest object-safe trait all four could implement to make it possible, and do it.
- Take the
rankedfunction and write three versions of the same signature: inline bounds, awhereclause, andimplin argument position. For the third, show a call that the first two accept and it rejects, and say in one sentence what capability the anonymous form gave up.