Module 9 · Lesson 22 of 112

Trait bounds, impl Trait, and trait objects

Constrain generic code with trait bounds, return opaque types with impl Trait, and use trait objects to dispatch across different concrete types.

  • Beginner to advanced
  • 10 min read
  • 30 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, with rustc and Cargo installed. No board required.

Your place in the module
By the end you can 4 objectives
  • Write single and multiple trait bounds on functions and implementation blocks
  • Distinguish caller-selected generic parameters from callee-selected opaque return types
  • Use borrowed and boxed trait objects to call methods on different concrete types
  • Identify method signatures that prevent dynamic dispatch and explain how a vtable supports it
Video coming soonTrait bounds, impl Trait, and trait objects
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Defining traits and the orphan rule
  • A trait declares the behavior and associated items that an implementation supplies or inherits.
  • Iterator implementations select one Item type per implementing type.
  • A supertrait is a requirement, while a blanket implementation supplies behavior to every type covered by its condition.
01

Trait bounds specify what generic code can do

3 min read

The last lesson defined traits and associated types. This lesson answers how to constrain generics with bounds and when to use impl Trait versus dyn Trait.

Linux hardware monitoring gives a concrete reason to care about this distinction. The kernel's hwmon interface exposes readings such as temperature and fan speed through sysfs attributes. A reporting program might represent those readings with separate Rust types because their values have different units. One function might select the largest temperature in a batch. Another might print a report that includes temperatures and fan speeds in the same list. The first operation needs comparison within one type. The second needs a shared reporting interface across types. Kernel hwmon sysfs interface

A generic function can name the operations it needs in its signature. In fn show<T: Summary>(value: &T), the bound T: Summary requires the caller's concrete type to implement Summary. The function can then call the methods in that trait. With T: A + B, the type must implement both traits. The compiler checks the requirements at each call, and the function body can use operations from both. Here is a function with two bounds for selecting a value from a slice.

rust
fn largest<T: PartialOrd + Clone>(values: &[T]) -> Option<T> {
    let (first, rest) = values.split_first()?;
    let mut best = first;
    for candidate in rest {
        if candidate > best {
            best = candidate;
        }
    }
    Some((*best).clone())
}

PartialOrd makes > available, and Clone makes it possible to return an owned value while reading from a borrowed slice. The loop compares references and retains a reference to the current candidate. It clones the selected value once at the end. split_first returns None for an empty slice. Here the ? returns that None from largest immediately. The same signature can place the requirements after the return type as where T: PartialOrd + Clone. A where clause is especially helpful when several type parameters have separate bounds.

The comparison contract matters. With ordinary integers, largest(&[4, 9, 9, 2]) returns Some(9). A strictly greater candidate replaces the current one, so equality leaves the earlier candidate selected. PartialOrd also permits incomparable values. For floating-point NaN, either comparison with > is false. If the first value is NaN, it stays selected in this implementation. If a later candidate is NaN, it is skipped. For the practice exercise, use inputs whose values are mutually comparable and describe that assumption in the function's contract. A bound tells you which operations are available. The algorithm still needs a policy for the results those operations can produce.

Bounds can also control which methods a generic type offers. The following Batch<T> can hold values of any ordinary concrete element type. Its peak method is available when the element type supports both operations needed by largest.

rust
struct Batch<T> {
    samples: Vec<T>,
}

impl<T> Batch<T> {
    fn len(&self) -> usize {
        self.samples.len()
    }
}

impl<T: PartialOrd + Clone> Batch<T> {
    fn peak(&self) -> Option<T> {
        largest(&self.samples)
    }
}

The compiler checks a call to peak against the bounds on the second impl block. A batch whose element type implements neither trait can still use len. Put requirements on the specific method or block that needs them. The type declaration itself can remain usable in contexts that require fewer operations. A where clause can also express bounds on an impl block, directly after Batch<T> in this example.

Checking a generic boundConcreteelementtypeInferredfrom thesliceCheck bothboundsPartialOrdand CloneUse genericfunctionCompare andcloneExit from step 2: Missing boundCompile errorConcreteelementtypeInferredfrom thesliceCheck bothboundsPartialOrdand CloneExit from step 2: MissingboundCompile errorUse genericfunctionCompare andclone
The same bounds govern the operations in a generic function and which concrete types can call it
02

Choose who determines the concrete type

3 min read

In a parameter, impl Trait is shorthand for a generic parameter constrained by a trait. For example, fn label(value: &impl Summary) -> String accepts a borrowed value of any concrete type that implements Summary, just as fn label<T: Summary>(value: &T) -> String does. You can combine bounds in the shorthand. &(impl Summary + Clone) borrows a value whose type implements both traits. The parentheses group the bounds under the reference.

A named type parameter is useful when the signature needs to express a relationship. With fn pair<T: Summary>(first: &T, second: &T), both references must fit the same T. With fn pair(first: &impl Summary, second: &impl Summary), each occurrence introduces its own type parameter. A temperature reading and a fan reading can therefore be passed together to the second signature. Both signatures use static dispatch for ordinary calls with concrete types. lets the compiler know which method belongs to each argument type.

In a return type, impl Trait serves a different purpose. In fn default_reading() -> impl Summary, the function implementation chooses the concrete return type and the signature exposes an opaque type. The caller can use the methods promised by Summary while leaving the concrete representation private. A return type of impl Summary + Clone also promises the caller that it can clone the returned value. Returning a named generic T with a bound would instead promise to produce the T selected for the call.

Here are two types we can use to exercise those signatures. They hold values supplied by the example program. The code operates on the readings in memory.

rust
trait Summary {
    fn detail(&self) -> String;

    fn summarize(&self) -> String {
        format!("Reading: {}", self.detail())
    }
}

#[derive(Clone)]
struct Temperature(i32);

#[derive(Clone)]
struct FanSpeed(u32);

impl Summary for Temperature {
    fn detail(&self) -> String {
        format!("{} m°C", self.0)
    }
}

impl Summary for FanSpeed {
    fn detail(&self) -> String {
        format!("{} RPM", self.0)
    }
}

fn default_reading() -> impl Summary + Clone {
    Temperature(42_000)
}

fn label(value: &impl Summary) -> String {
    value.summarize()
}

Both implementations supply detail and inherit the default summarize. label(&Temperature(42_000)) and label(&FanSpeed(900)) each call the method for their respective type. label(&default_reading()) also works because the opaque return type satisfies the bound. The caller can save the returned value, clone it, and summarize either copy. Accessing the tuple field through the opaque return type is unavailable because the signature exposes the trait interface.

For a given instantiation, every return path for an impl Summary return must yield the same concrete type. An if that returns Temperature in one branch and FanSpeed in the other fails that requirement even though each type implements Summary. Two branches returning different Temperature values work. A closed set of alternatives can also use a single enum type that implements Summary by matching its variants. When the API needs to accept different concrete types through the same interface and select their method implementations at runtime, use a trait object.

Three signature choicesParameterimpl TraitReturn implTraitTrait objectConcrete typeChosen bycallerChosen byfunctionErased atinterfaceOne call siteConcrete typeknownHidden typefixedConcrete typecan varyDispatchStatic forconcretetypesStatic forconcretetypesThroughvtable
The signature determines who chooses the concrete type and how a method call is resolved
03

Dispatch through a trait object

5 min read

Use &dyn Summary when a function needs to borrow a value and call its Summary methods regardless of its concrete type. Use Box<dyn Summary> when the caller should own the erased value, as in a returned reading or a collection of owned readings. A Box typically owns a heap allocation. A borrowed trait object can refer to an existing local value, so creating the trait object reference itself requires no heap allocation. The borrow still limits how long the reference can be used.

rust
fn label_dyn(value: &dyn Summary) -> String {
    value.summarize()
}

fn select_reading(report_fan: bool) -> Box<dyn Summary> {
    if report_fan {
        Box::new(FanSpeed(900))
    } else {
        Box::new(Temperature(42_000))
    }
}

fn report() -> Vec<String> {
    let temp = Temperature(42_000);
    let fan = FanSpeed(900);
    let readings: [&dyn Summary; 2] = [&temp, &fan];

    let mut lines = Vec::new();
    for reading in readings {
        lines.push(label_dyn(reading));
    }

    let owned = select_reading(true);
    lines.push(label_dyn(owned.as_ref()));
    lines
}

Calling report() returns ["Reading: 42000 m°C", "Reading: 900 RPM", "Reading: 900 RPM"] (a real run with rustc 1.100.1). The array has one element type, &dyn Summary. The compiler coerces &temp and &fan to that type. In select_reading, each branch similarly coerces its concrete box to Box<dyn Summary>. Within label_dyn, the summarize call works with whichever implementation arrived. is what lets the same call in the loop handle both readings. The compiler still checks that each value implements Summary when it creates the trait object. A runtime condition alone can also choose between two branches with separate static calls. Dynamic dispatch is needed for the interface shown here, where one call works across an extensible set of implementations and has only the trait object available.

A trait used this way must be dyn-compatible, also called object safe. Summary qualifies because its methods receive &self, have callable signatures independent of the hidden type, and have no generic type parameters. Other supported receiver forms include &mut self and self: Box<Self>. A dispatchable method cannot return bare Self or accept a separate argument of type Self. The caller would need to know which concrete type to return or pass. A generic method could require a different compiled implementation for each type argument, which the trait object's method table cannot supply. Dispatchable methods also cannot use async fn or a return-position impl Trait in their signatures.

A method that requires a concrete type can be declared with where Self: Sized. For example, adding fn duplicate(&self) -> Self where Self: Sized; to Summary would let each implementation define that operation while keeping dyn Summary usable for summarize. The bound excludes duplicate from dispatch through the trait object. A Self: Sized bound on the whole trait instead prevents using it as a trait object. Dyn compatibility also requires compatible supertraits, excludes associated constants and generic associated types, and allows ordinary associated types. For a trait Source declaring type Item, a trait object can bind the associated type explicitly, as in &dyn Source<Item = i32>.

One distinction between multiple bounds and trait objects is worth checking in your own signatures. T: Summary + Clone and impl Summary + Clone both support two trait bounds. A trait object can name one principal trait and add auto traits such as Send. For example, Box<dyn Summary + Send> requires a concrete implementor that also satisfies Send. To expose methods from two dyn-compatible ordinary traits together, define a dyn-compatible trait with both as supertraits and use that trait as the principal trait.

Trait object pointerTrait object pointerData pointerConcrete valueVtable pointerMethod entrySelects the concrete implementationTrait object pointerData pointerConcrete valueVtable pointerMethod entrySelects the concreteimplementation
A trait object reference carries the address of the value and the vtable used to select its method
Going deeperExplore the mechanism

A pointer to a trait object is a fat pointer. It holds a data pointer to the concrete value and a vtable pointer for the concrete implementation of the trait. A virtual method call uses the vtable entry for that method and passes the data pointer so the selected implementation can access the original value. Vtable metadata also supports operations such as dropping the erased value when ownership requires it. Treat this as a model of Rust's dispatch, since the exact vtable layout is a compiler implementation detail and Rust does not promise a stable vtable ABI for C.

Static dispatch often allows a direct call or lets the optimizer inline a short method. When the destination remains unknown to the optimizer, dynamic dispatch involves a vtable lookup and an indirect call. That can make inlining harder and may affect branch prediction in a loop that alternates between implementations. The optimizer can sometimes recover the target and optimize the call. Allocation, when present, is a separate cost of the chosen ownership representation. A borrowed trait object can incur indirect dispatch with no allocation of the receiver.

Monomorphization can generate specialized machine code for each concrete instantiation of a generic function. With many instantiations of a substantial function, this can increase compile time and executable size. A function accepting &dyn Summary can share its body across implementations while the individual method implementations still exist. Actual size depends on what the compiler and linker retain and combine. Runtime impact depends on the work around the call. A short method in a tight in-memory loop presents a different cost profile from a reporting loop that also reads from a file descriptor and formats text. Compare equivalent work in optimized builds to assess the dispatch cost on your target. read(2)

Review the examples by identifying the choice each signature makes. largest uses bounds to state what an arbitrary element type must support. default_reading chooses one concrete type internally and exposes its promised operations. label_dyn receives a borrowed value through an interface that can represent multiple concrete types at runtime. The next lesson, Conversion and operator traits, examines the contracts behind conversions and operators, including how expressions like the comparison in largest use traits.

Key takeaways

  • Trait bounds specify the operations generic code can use.
  • Each return-position impl Trait denotes a single hidden concrete type for a given instantiation.
  • A trait object pointer carries a data pointer and a vtable pointer.
  • A method restricted to Self: Sized can coexist with dynamically dispatched methods on the same trait.
Reflect
  1. Explain to a colleague, in two sentences: write single and multiple trait bounds on functions and implementation blocks
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close