skip to content

In Rust, why does a generic `max_reading<T>` function that compares readings with `>` fail to compile until `T` gets a bound?

level: juniorimportance: must knowfreq 75%

answer

  1. checked at the definition, not per call
  2. the body sees only promised operations
  3. which std trait backs the > operator
  4. E0369 in the body, E0277 at the call

basics

~20 s

Rust type-checks a generic body once, against its bounds alone. An unbounded T promises no comparison, so r > best fails with E0369; adding T: PartialOrd permits it, and callers whose type lacks PartialOrd get E0277.

solid answer

~50 s

rustc checks a generic function once, at its definition, assuming nothing about `T` beyond its declared bounds. An unbounded `T` can be moved, borrowed and dropped, but not compared, printed, cloned or added, so `if r > best` is rejected with E0369 ("binary operation `>` cannot be applied to type `&T`"), and the help suggests restricting `T` with `PartialOrd`. Writing `fn max_reading<T: PartialOrd>(readings: &[T]) -> Option<&T>` does two jobs: it unlocks `>` inside the body, and it becomes a contract every caller must meet. Pass a slice of a struct that does not implement `PartialOrd` and the error moves to the call site as E0277, pointing at the bound. So a generic body that type-checks has no type errors for any `T` that meets its bounds, and each error lands where the contract is broken.

code

rust · 12 lines
rust
fn max_reading<T>(readings: &[T]) -> Option<&T> {
    let mut best = readings.first()?;
    for r in readings {
        if r > best {
            best = r;
        }
    }
    Some(best)
}
fn main() {
    println!("{:?}", max_reading(&[3, 9, 4]));
}

go deeper

for a junior

Recall that a generic body may only use operations its bounds promise, and know which std trait backs comparison, equality, printing and cloning.

for a middle

Explain the two error sites: E0369 or E0277 inside the body when a bound is missing, E0277 at the call when a caller's type falls short, and how bounds propagate to generic callers.

for a senior

Show you pick the weakest sufficient bound, such as PartialOrd over Ord so float readings still work, and read rustc's help lines to tighten signatures deliberately.

for a principal

Treat bounds as a public contract: each added bound narrows who can call an API, so reviewers should question every bound the body does not strictly need.

## The rule: a generic body is checked against its bounds A **generic function** such as `fn max_reading<T>(readings: &[T]) -> Option<&T>` declares a **type parameter** `T` that the caller fills in later. Rust does not wait for the caller to type-check the body. rustc checks the body **once, at the definition**, and inside it the only facts it knows about `T` are the ones written as **trait bounds** (`T: SomeTrait`). The Reference states the rule from the other side: when a generic item has a bound `T: Trait`, the body may call that trait's methods and use its associated items, and every use of the item must satisfy the bound. That makes a bound two things at once: - a **permission** for the body, which may now use whatever the trait provides; - a **requirement** on every caller, whose concrete type must implement the trait. ## What an unbounded `T` allows With no bound at all, a `T` value (implicitly `Sized`) can still be: - moved, returned, stored in a struct field or a `Vec<T>`; - borrowed as `&T` or `&mut T` and handed to other code that is equally generic; - dropped at the end of its scope. It cannot be compared, printed, cloned, hashed or added, because each of those operations is a trait method. The table maps the common operations to the bound that unlocks them: | Operation in the body | Bound needed | |---|---| | `a > b`, `a < b` | `T: PartialOrd` | | `a == b` | `T: PartialEq` | | `println!("{}", a)` | `T: Display` | | `println!("{:?}", a)` | `T: Debug` | | `a.clone()` producing a `T` | `T: Clone` | | `a + b` | `T: Add` | | copying `*r` out of a `&T` | `T: Copy` | ## Error one: E0369 inside the body In the statistics module, a first draft of `max_reading` walks the slice and keeps the largest reading. `readings.first()?` gives a `&T`, the loop gives `&T` values, and `r > best` compares two references. rustc 1.99.1 stops on the comparison with **E0369**, "binary operation `>` cannot be applied to type `&T`", and its help line proposes `T: std::cmp::PartialOrd`. Comparing references works once `T: PartialOrd` holds, because std implements `PartialOrd` for `&A` whenever `A: PartialOrd`. Notice where the error appears: in the generic body, before anyone has called the function. No caller needs to exist for this check to run. ## Error two: E0277 at the call site Once the bound is in place the body compiles, and the burden moves to callers. If code passes `&[Sensor { id: 1 }, Sensor { id: 2 }]` where `Sensor` implements nothing, rustc reports **E0277** at the call: "can't compare `Sensor` with `Sensor`", with the note "required by a bound in `max_reading`" and a suggestion to annotate `Sensor` with `#[derive(PartialOrd)]`. The function's body is not mentioned, because it has already been checked. The same happens one level up. A second generic function `fn report<T>(readings: &[T])` that calls `max_reading(readings)` fails with E0277 inside `report`, and rustc suggests adding `T: PartialOrd` to `report` too. Bounds therefore **propagate upward**: every generic caller must restate the bounds of what it calls. ## Choosing the smallest bound 1. Write the body first and let the compiler list what it needs; the `help:` lines name the trait. 2. Pick the **weakest** trait that covers the body. `PartialOrd` is enough for `>`; demanding `Ord` would reject `&[f64]`, because `f64` has no total order (NaN compares unordered with every value). 3. Add `Clone` or `Copy` only when the body must produce an owned `T` from a borrowed one. 4. Combine traits with `+` (`T: PartialOrd + Copy`) when the body needs several. ## Why Rust works this way Checking the body once against declared bounds means a library author learns about a broken body immediately, and a caller learns about a missing trait at the line that caused it, not deep inside someone else's code. Unlike C++ templates, which are checked per instantiation, a Rust generic that type-checks will not produce new type errors in its body for a type that satisfies its bounds. The bounds are also the documentation: the signature alone says what a caller's type must support.

  • If the body ends with `Some(best.clone())` and the return type is `Option<T>`, but the only bound is `T: PartialOrd`, what does rustc do?
    It fails with E0308, expected `T`, found `&T`. Without `T: Clone`, method lookup finds `Clone` on the reference itself, since `&T` is always `Clone`, so the call copies the reference; rustc adds the note "`T` does not implement `Clone`, so `&T` was cloned instead". Adding `T: Clone` makes `best.clone()` produce an owned `T`.
  • Why does `max_reading` accept `&[f64]` with `T: PartialOrd` when a version bounded by `T: Ord` would not?
    `f64` implements `PartialOrd` but not `Ord`, because NaN is unordered with every value, so no total order exists. An `Ord` bound rejects `&[f64]` with E0277. `PartialOrd` is enough for `>`, with one consequence: every comparison involving NaN is false, so a NaN in the first slot is never replaced.
  • A generic `report<T>` calls `max_reading` without declaring any bound. Where is the error, and what fixes it?
    rustc reports E0277 inside `report`, at the call to `max_reading`, because `report` cannot prove `T: PartialOrd`. Its help suggests `fn report<T: std::cmp::PartialOrd>`. Every generic caller has to restate the bounds of the generic functions it calls.

A job posting lists the required certifications: the role may assume only those skills, and an applicant without one is turned away at the door, not halfway through a shift.

  • Rust checks a generic body separately for every concrete type it is called with.
  • An unbounded T can be compared with > because every type implements PartialOrd.
  • Bounding by Ord is always the right choice for comparing readings.
  • A missing bound is only reported once someone calls the function.
  • A trait bound makes each comparison go through a lookup table at run time.