Systems Design Questions · 18 min · free lesson

dyn Trait vs Generics

Generics preserve concrete types; trait objects provide a common interface with dynamic dispatch.

Core idea

Choose dispatch from API flexibility, ownership and measured performance; neither choice guarantees a smaller or faster program.

One generic function template compiled into separate functions for i32 and String at compile time, with no runtime type switch.
The diagram shows the generic specialization model. Compare it with borrowed trait objects in the example; generated code and performance depend on optimization.

Understand it

Generic code can be specialized for concrete types, enabling direct calls and inlining. Trait objects provide a common interface with dynamic dispatch. Those mechanisms influence optimization and code size, but neither guarantees a speed or binary-size ranking: optimizations, method bodies and call sites all matter.

With a generic T: Trait, callers supply a concrete type and the compiler can specialize code for that type. This often permits inlining and avoids a per-call virtual dispatch, but different concrete instantiations can increase code size and compile time. With dyn Trait, a trait object pairs data with a vtable for methods allowed by object safety. Calls through it use dynamic dispatch, and a collection can hold different concrete implementations behind one pointer type.

Give the interviewer a design example. A hot inner loop operating on one known iterator type may benefit from generics. A plugin registry holding several handler implementations may need Box<dyn Handler> because the concrete types differ at runtime. The actual speed difference must be measured; cache behavior and work inside each method can dominate dispatch overhead. Generic code can still be large for reasons beyond one simple 'copy per type' story, and trait objects still involve allocation only when you choose a heap-owning pointer such as Box.

Mention object safety when relevant: not every trait can become dyn Trait, especially methods returning Self or generic methods without suitable bounds. A trait object also encodes a lifetime for the underlying data. State the required flexibility, binary-size pressure, and call-site performance before choosing. The best answer is a decision tied to constraints, not a universal claim that one mechanism is faster.

A borrowed &dyn Trait does not allocate by itself. Box<dyn Trait> additionally chooses heap ownership. An enum is another way to represent a closed set of alternatives, so heterogeneous data does not universally require dyn. Use trait objects when an open set of implementations should share a runtime interface; use an enum when a known finite set and exhaustive matching suit the design. The trait must be dyn-compatible for a trait-object interface.

Interview follow-up: Why is an async method not directly dispatchable through dyn Trait? Compare a generic caller with an explicitly boxed future.

Read the code

trait Shape { fn label(&self) -> &'static str; }
struct Circle;
struct Square;
impl Shape for Circle { fn label(&self) -> &'static str { "circle" } }
impl Shape for Square { fn label(&self) -> &'static str { "square" } }
fn static_label<S: Shape>(shape: &S) -> &'static str { shape.label() }
fn dynamic_label(shape: &dyn Shape) -> &'static str { shape.label() }
fn main() {
    let circle = Circle;
    let square = Square;
    let mixed: [&dyn Shape; 2] = [&circle, &square];
    assert_eq!(static_label(&circle), "circle");
    for shape in mixed { println!("{}", dynamic_label(shape)); }
}

The generic call keeps a concrete type; borrowed trait objects let two implementations share one interface. This example uses no Box and makes no benchmark claim.

Practice starter

trait Shape { fn area(&self) -> u32; }
struct Square(u32);
impl Shape for Square { fn area(&self) -> u32 { self.0 * self.0 } }
fn area(shape: &dyn Shape) -> u32 { shape.area() }
fn main() { assert_eq!(area(&Square(3)), 9); }

Practise this code in Playground ↗

Try it

Compare a generic call with a trait object and name the trade-off.

What success looks like: You mention monomorphisation, binary size, and the vtable.

Check your understanding

Which statement correctly describes passing &Square(3) as &dyn Shape?

Reveal the answer
  1. Every conversion to &dyn Trait allocates a separate heap object.
  2. The borrowed trait object uses dynamic dispatch without requiring a Box allocation.
  3. Using dyn Trait requires all implementation methods to be monomorphized for the caller.

Dispatch and allocation are separate choices: &dyn Trait borrows existing storage; Box<dyn Trait> also owns allocated storage.

Go deeper

Common misconception: Using dyn Trait requires all implementation methods to be monomorphized for the caller.

A &dyn Shape call is not monomorphized for the caller. It finds the method through the vtable at runtime; specializing per concrete type is what generics do.

  1. Identify the contract: Generics preserve concrete types; trait objects provide a common interface with dynamic dispatch.
  2. Trace the concrete example: The generic call keeps a concrete type; borrowed trait objects let two implementations share one interface. This example uses no Box and makes no benchmark claim.
  3. Test the changed constraint: Why is an async method not directly dispatchable through dyn Trait? Compare a generic caller with an explicitly boxed future.

Transfer challenge: Why is an async method not directly dispatchable through dyn Trait? Compare a generic caller with an explicitly boxed future.

Connections

  • Box, Rc, and Arc: Ownership and allocation choices
  • Reasoning About unsafe: Sound abstractions and invariants
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: dyn Trait vs Generics (courseId "interview", lessonId "q-dyn-generics")
Link: https://crabrix.com/learn/interview/q-dyn-generics/
Goal: Choose dispatch from API flexibility, ownership and measured performance; neither choice guarantees a smaller or faster program.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=interview/q-dyn-generics) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.