skip to content

Traits and Generics

Traits are Rust's interfaces and generics are checked against them, with static or dynamic dispatch as a choice. Interviewers test bounds, trait objects, coherence and impl Trait.

on this pageshow

explore

questions

page 1 of 2

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.
open as a page

In Rust, how does a trait give a method a default body, and what happens when an implementing type overrides it?

level: juniorimportance: must knowfreq 78%

basics

~20 s

A trait method written with a body is a default: implementors inherit it unless their impl defines the same method, which replaces it completely. Defaults may call required methods; an override cannot call the default it replaced.

open as a page

In Rust, why return `impl Iterator<Item = &i32>` from a function that filters a borrowed slice, and what may the caller do with it?

level: juniorimportance: must knowfreq 62%

basics

~20 s

The real type is a Filter adapter holding a closure, whose type cannot be written. Returning impl Iterator hands it back unboxed and lazy; the caller sees an opaque type and may use only Iterator's methods.

open as a page

In a Rust drawing app, why must a canvas holding circles and rectangles together be a `Vec<Box<dyn Shape>>` rather than a `Vec<T>` with `T: Shape`?

level: juniorimportance: must knowfreq 76%

basics

~20 s

A Vec has one element type and a generic T: Shape is one concrete type, so circles and rectangles cannot share a Vec<T>. Box<dyn Shape> erases each concrete type behind a pointer and a vtable, giving every element one type.

open as a page

In Rust, why does the `Iterator` trait declare `type Item` instead of being generic as `Iterator<T>`, and when is a type parameter the better choice?

level: middleimportance: must knowfreq 68%

basics

~20 s

With an associated type, a type implements the trait at most once and the implementer fixes Item, so callers never annotate it. A type parameter allows one impl per argument type, which suits inputs such as Add's Rhs.

open as a page

In Rust, when should bounds like `T: Copy + Into<f64>` move into a `where` clause, and what can only a `where` clause express?

level: middleimportance: must knowfreq 62%

basics

~20 s

Inline bounds and a where clause mean the same thing for a type parameter; where is chosen once bounds grow long or numerous. Only where can bound a type that is not a declared parameter, such as f64: From<T> or Vec<T>: Debug.

open as a page

In a Rust application crate, why can't you write `impl serde::Serialize for std::time::SystemTime` to emit Unix milliseconds, and what do you write instead?

level: middleimportance: must knowfreq 55%

basics

~20 s

Serialize belongs to serde and SystemTime to std, so the impl breaks Rust's orphan rule (E0117); serde also already implements it, and coherence allows one impl per pair. Wrap the time in a local newtype and implement Serialize for that.

open as a page

In Rust, what changes when `impl Trait` moves from a function parameter to its return type, and who chooses the concrete type?

level: middleimportance: must knowfreq 70%

basics

~20 s

In a parameter, impl Trait is an anonymous generic: the caller picks the type and the function is monomorphized per type. In the return type, the function body picks one hidden type and the caller sees only the trait.

open as a page

In Rust, what does a `&dyn Shape` hold at run time, and what does a method call through it cost versus a generic call?

level: middleimportance: must knowfreq 62%

basics

~20 s

A pointer to dyn Shape is a fat pointer: a data pointer plus a vtable pointer, the vtable holding size, alignment, drop glue and method pointers. Each call is indirect through it and generally not inlined; generics compile a direct call per type.

open as a page

In a Rust generic function over `C: Container`, how do you require `Container`'s associated `Item` to be `u32`, or to implement `Display`?

level: juniorimportance: should knowfreq 55%

basics

~20 s

Pin it with an equality constraint, C: Container<Item = u32>, or constrain it with where C::Item: Display. Inside the trait it is written Self::Item; when two bounds both declare an Item, write <C as Container>::Item.

open as a page

In Rust, may your crate implement its own trait for `String`, a std trait for its own struct, and `std::fmt::Display` for `Vec<u8>`?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Yes, yes, no. Rust's orphan rule lets a crate implement a trait for a type only when the trait or the type is defined in that crate; Display and Vec<u8> both come from std, so rustc rejects that impl with E0117.

open as a page

In Rust, how do you write one function that takes `[i32; 3]` and `[i32; 5]` arrays by value, and what does its `N` stand for?

level: juniorimportance: should knowfreq 40%

basics

~20 s

Declare a const generic parameter: fn sum<const N: usize>(values: [i32; N]). N is a usize value fixed at compile time, inferred from the argument's array type, and rustc compiles one copy of sum for each length the program uses.

open as a page

In Rust, what does a trait's associated const such as `const ID: u32;` offer over a method returning it, and where does it stop working?

level: middleimportance: should knowfreq 35%

basics

~20 s

An associated const is a compile-time value each impl supplies, read as M::ID without an instance and usable in const contexts for concrete types. Generic code cannot use it as an array length or a pattern, and it rules out dyn.

open as a page

In Rust, why does `let n = "42".parse().unwrap();` fail when `n` is only printed afterwards, and how does `parse::<i32>()` fix it?

level: middleimportance: should knowfreq 55%

basics

~20 s

str::parse is generic over its return type F: FromStr, and printing n does not pin F, so rustc stops with E0284, type annotations needed. The turbofish parse::<i32>() supplies the type argument at the call; let n: i32 works equally well.

open as a page

In Rust, if `SmsNotifier` has an inherent `channel` method and two traits also define `channel`, which does `s.channel()` call, and how do you call each?

level: middleimportance: should knowfreq 55%

basics

~20 s

Method-call syntax picks the inherent channel, because inherent methods are searched before trait methods for the same receiver type. Notifier::channel(&s) and Billing::channel(&s) call the trait versions; a function with no self needs <SmsNotifier as Notifier>::kind().

open as a page

In Rust, what does declaring `trait Loud: Notifier` require of an implementing type, and which methods can `Loud`'s default bodies call?

level: middleimportance: should knowfreq 42%

basics

~20 s

trait Loud: Notifier means Self: Notifier: a type may implement Loud only if it also implements Notifier in its own impl block. Loud's default bodies, and any code bounded by Loud, can call Notifier's methods on self.

open as a page

In Rust, why does rustc reject `n.send(..)` with E0599 when `EmailNotifier` implements the `Notifier` trait, and how do you fix it?

level: middleimportance: should knowfreq 45%

basics

~20 s

Trait methods are only candidates for method-call syntax when the trait itself is in scope. Importing the type is not enough; add use crate::notify::Notifier (or use ... as _) in the calling module, or call Notifier::send(&n, ..) by path.

open as a page

In Rust, why does `-> impl Fn(u32) -> u32` reject an if/else returning two different capturing closures, and how do you fix it?

level: middleimportance: should knowfreq 55%

basics

~20 s

Return-position impl Trait stands for one concrete type, and every closure has its own unique type, so two capturing closures give E0308. Return one move closure over the varying data, or box both as Box<dyn Fn>.

open as a page

In Rust, how can a `Matrix<const R: usize, const C: usize>` type make multiplying a 2x3 matrix by another 2x3 matrix a compile error?

level: middleimportance: should knowfreq 30%

basics

~20 s

Give mul the signature fn mul<const K: usize>(&self, rhs: &Matrix<C, K>) -> Matrix<R, K>. The right side must have C rows, so a 2x3 times 2x3 call is a type mismatch (E0308), and the result's shape is computed in its type.

open as a page

In a Rust typestate request builder, why does `RequestBuilder<S>` need a `PhantomData<S>` field, and what does that field cost at run time?

level: middleimportance: should knowfreq 28%

basics

~20 s

Rust rejects a struct whose type parameter appears in no field, error E0392. PhantomData<S> is that use; it is zero-sized, so RequestBuilder<NoUrl> is exactly as large as its real fields and the marker costs nothing at run time.

open as a page

In a Rust `Cache<K, V>`, why put bounds like `K: Eq + Hash` on impl blocks instead of the struct, and how does a `dump()` method exist only for displayable caches?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Bounds on an impl block apply only to that block's methods, so new and len stay bound-free while insert needs K: Eq + Hash and dump needs Display. Bounds on the struct itself must be restated by every impl and every generic user.

open as a page

After a Rust generic `mean<T>` is called with many element types, build time and binary size grow; what does monomorphization do, and how do you contain it?

level: seniorimportance: should knowfreq 50%

basics

~20 s

rustc compiles a separate copy of a generic function, and of every generic helper it calls, for each distinct set of concrete type arguments. Calls stay direct and inlinable, but copies multiply; keep generic shells thin and delegate to a non-generic inner function.

open as a page

A Rust crate defines `trait Encode` with a blanket `impl<T: Display> Encode for T`; why does adding `impl Encode for SystemTime` fail with E0119 although `SystemTime` has no `Display` impl?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Rust's overlap check must survive std adding impl Display for SystemTime in a later release, when both impls would apply. rustc assumes an impl is absent only where no other crate could add it, as for a local type.

open as a page

In Rust, why does rustc accept `impl From<Celsius> for f64` and `impl IntoIterator for &Readings`, yet reject `impl fmt::Display for Vec<Celsius>` with E0117?

level: seniorimportance: should knowfreq 25%

basics

~20 s

The orphan rule needs one local type anywhere in the impl header, with no uncovered type parameter before it. Celsius as From's argument qualifies; &Readings is local because & is fundamental; Vec<Celsius> is a foreign Vec.

open as a page

On Rust 2024, why does a caller get E0597 when `above(&readings, &limit)` returns `impl Iterator<Item = &'a i32>` and `limit` is dropped first, and how does `use<..>` fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

On the 2024 edition, return-position impl Trait captures every in-scope lifetime, so the result counts as borrowing limit even if the body copied it. Writing + use<'a> (stable since 1.82) captures only the slice's lifetime.

open as a page

A Rust `Plugin` trait with a generic `configure<T>` method and a `duplicate(&self) -> Self` method fails with E0038 at `Box<dyn Plugin>`: why, and how do you fix it?

level: seniorimportance: should knowfreq 52%

basics

~20 s

A vtable needs one function pointer per method: a generic method has unboundedly many instantiations and a Self return has no size behind dyn, so Plugin is not dyn compatible. Adding where Self: Sized to those two methods removes them from the vtable.

open as a page

In Rust 1.86 and later, how do you get a concrete `Metrics` plugin back out of a `Box<dyn Plugin>`, and what did code need before trait-object upcasting?

level: seniorimportance: should knowfreq 34%

basics

~20 s

Declare trait Plugin: Any, upcast the &dyn Plugin to &dyn Any (allowed since Rust 1.86) and call downcast_ref::<Metrics>(), or upcast the Box to Box<dyn Any> and call downcast. Before 1.86 each plugin implemented an as_any(&self) -> &dyn Any method.

open as a page

In a Rust typestate HTTP request builder, how do you make calling `send()` before setting a URL a compile error instead of a runtime check?

level: seniorimportance: should knowfreq 32%

basics

~10 s

Make the state a type parameter: url(self, ...) consumes a RequestBuilder<NoUrl> and returns a RequestBuilder<HasUrl>, and send is defined only in impl RequestBuilder<HasUrl>. An early send is E0599; reusing the consumed builder is E0382.

open as a page

Your team's Rust service exposes a handler-registration API; should handlers be generic type parameters or boxed `dyn Handler` values, and which default would you set?

level: principalimportance: should knowfreq 40%

basics

~20 s

Use generics where the handler type is known at compile time and calls are hot; use Box<dyn Handler + Send + Sync> where the set is open, mixed or chosen at run time. A sound default for a router is the hybrid: accept impl Handler, store it boxed.

open as a page

As a Rust library lead, what rule do you set for public functions that return iterators: `impl Iterator`, a named iterator type, or `Box<dyn Iterator>`?

level: principalimportance: should knowfreq 30%

basics

~20 s

Inside an application, return impl Iterator: it is zero-cost and the code is easy to change. In a library's public API, prefer a named iterator struct when callers may store, clone or name the result, as std does with str::Lines. Use Box<dyn Iterator> only when one signature must return different types at run time.

open as a page

showing 1–30 of 36