Skip to content
rusthacks.dev
Generics

Traits Generics and Trait Objects and How to Choose

A guide to choosing between generics, impl Trait, trait objects and enums in Rust, with one example solved four ways and the costs of each.

18 min read
Summarize in AI
Flat illustration for the post “Traits Generics and Trait Objects and How to Choose”, composed around generics.

Rust gives you four ways to write one piece of code over many types: a generic function, impl Trait, a trait object, and an enum. They overlap more than the documentation admits, and picking between them is mostly a matter of answering one question: who decides the concrete type, and when? If the compiler can know it, generics win. If it is only known while the program runs, you need dyn Trait. If you own every possible type and the list is short, an enum beats both. This guide solves one problem all four ways, shows what each costs in compile output and in measured nanoseconds, and ends with the boundary cases where the usual advice flips.

Everything here compiles and runs on Rust 1.99, edition 2024, with no dependencies. The benchmark numbers come from an Apple M1 Max in release mode. It assumes you have read the Rust language tour and know what a trait and a struct are.

The problem: a few shapes and one total

The running example is deliberately dull, because the interesting part is the dispatch and not the domain. There are two kinds of shape, each with an area, and we want to compute areas in four different situations. The trait, the two structs and all four solutions fit in one file:

src/main.rsrust
use std::f64::consts::PI;

trait Shape {
    fn area(&self) -> f64;
}

struct Circle(f64);
struct Rect(f64, f64);

impl Shape for Circle {
    fn area(&self) -> f64 {
        PI * self.0 * self.0
    }
}

impl Shape for Rect {
    fn area(&self) -> f64 {
        self.0 * self.1
    }
}

fn describe<S: Shape>(s: &S) -> String {
    format!("area {:.2}", s.area())
}

fn describe_impl(s: &impl Shape) -> String {
    format!("area {:.2}", s.area())
}

fn total(shapes: &[Box<dyn Shape>]) -> f64 {
    shapes.iter().map(|s| s.area()).sum()
}

enum AnyShape {
    Circle(f64),
    Rect(f64, f64),
}

impl AnyShape {
    fn area(&self) -> f64 {
        match self {
            AnyShape::Circle(r) => PI * r * r,
            AnyShape::Rect(w, h) => w * h,
        }
    }
}

fn main() {
    println!("generic: {}", describe(&Circle(1.5)));
    println!("impl:    {}", describe_impl(&Rect(2.0, 3.0)));

    let mixed: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Rect(2.0, 4.0))];
    println!("dyn:     {:.2}", total(&mixed));

    let closed = [AnyShape::Circle(1.0), AnyShape::Rect(2.0, 4.0)];
    println!("enum:    {:.2}", closed.iter().map(AnyShape::area).sum::<f64>());

    println!("size of &dyn Shape: {} bytes", std::mem::size_of::<&dyn Shape>());
    println!("size of &Circle:    {} bytes", std::mem::size_of::<&Circle>());
    println!("size of AnyShape:   {} bytes", std::mem::size_of::<AnyShape>());
}

Run it with cargo run and it prints:

Text
generic: area 7.07
impl:    area 6.00
dyn:     11.14
enum:    11.14
size of &dyn Shape: 16 bytes
size of &Circle:    8 bytes
size of AnyShape:   24 bytes

Read the file from the top. trait Shape declares one method, area, that takes &self and returns an f64. The two structs are tuple structs holding the radius, or the width and height. Each gets its own impl Shape block, which is where the compiler learns that Circle and Rect can be treated alike.

describe<S: Shape> is the generic version. The angle brackets introduce a type parameter S, and S: Shape is the bound that says only types implementing Shape may be passed. Inside the body, the compiler is allowed to call s.area() because the bound promises the method exists. describe_impl is the same function written with impl Shape in argument position. It is shorthand for an anonymous generic parameter, and the two produce identical machine code. The only difference visible to a caller is that with impl Shape you cannot write describe::<Circle>(...) to pick the type by hand.

total takes &[Box<dyn Shape>]. This is the trait object version, and it is the only one of the three that can accept a slice holding both circles and rectangles at once, because every element has the same type: Box<dyn Shape>. What differs is the value behind the box, and the call to area finds the right code at run time. The last version, AnyShape, drops the trait entirely. It is an enum with one variant per case, and match picks the arithmetic. It also holds a mix of circles and rectangles, without an allocation per element.

The three size_of lines at the bottom are the cheapest way to see what is different. A reference to a concrete Circle is 8 bytes, one pointer. A reference to dyn Shape is 16 bytes, because it is a fat pointer: one word for the data, one word for the vtable. The enum is 24 bytes, a tag plus room for the largest variant (the rectangle's two floats), whichever variant it happens to hold.

Generics: one copy per type

A generic function is a template. When the compiler sees describe(&Circle(1.5)) and describe(&Rect(2.0, 3.0)), it type-checks the body once against the bound, then generates two separate machine-code functions, describe::<Circle> and describe::<Rect>. This is called monomorphization, and generics and monomorphization follows it down to the assembly. The consequences are all good for speed and all bad for size.

The speed consequence is that every call is a direct call to a known address, and the optimizer can inline it, hoist work out of the loop around it, and vectorize across iterations. A generic summing loop over a slice of Circle can compile down to a handful of multiply-add instructions with the method body gone entirely. A trait object loop cannot do that, because the compiler does not know which function it is about to call.

The size consequence is that every distinct type you instantiate with adds a copy of the function and everything it calls generically. A utility used with forty types is forty copies. In ordinary application code this is invisible. In a library that is instantiated with many types, or in a binary that has to fit in a small flash chip, it is the main cost of the approach, and it also shows up as compile time, since the compiler does the optimization work once per copy. The tools to measure it are cargo llvm-lines and cargo bloat; run them before you guess.

A generic function also commits the caller to one concrete type per call. You cannot build a Vec<S> that holds circles and rectangles, because Vec<S> is a vector of one S. That limitation is not a flaw to work around. It is the reason the generic code is fast: the compiler knows the size and layout of every element.

The bound syntax scales past the single-trait case. S: Shape + Clone requires both, and a where clause moves a long list out of the signature, as trait bounds and where clauses explains. When you call a generic function with a type that does not satisfy the bound, the compiler stops with E0277, the trait bound is not satisfied, and names the missing impl. That error is the generic world's version of a type error and is nearly always a pointer to the one line you need to add.

impl Trait: two meanings, one keyword

In argument position, impl Trait is generics with less typing, as shown above. In return position it means something different, and it is the source of most of the confusion. A function returning impl Shape promises the caller "you get some type that implements Shape" and keeps the identity of that type hidden. The function still returns exactly one concrete type. It is chosen by the function body, not by the caller, and the compiler knows it. This is what makes it useful for returning closures and iterator chains whose real types are unwritable.

The trap is believing that impl Shape behaves like a trait object and lets the body return different types on different branches. It does not:

src/main.rsrust
trait Shape {
    fn area(&self) -> f64;
}
struct Circle(f64);
struct Rect(f64, f64);
impl Shape for Circle {
    fn area(&self) -> f64 { 3.14 * self.0 * self.0 }
}
impl Shape for Rect {
    fn area(&self) -> f64 { self.0 * self.1 }
}

fn pick(round: bool) -> impl Shape {
    if round { Circle(1.0) } else { Rect(1.0, 2.0) }
}

fn main() {
    println!("{}", pick(true).area());
}

The compiler rejects it, and the message is worth reading in full:

Text
error[E0308]: `if` and `else` have incompatible types
  --> src/main.rs:14:37
   |
14 |     if round { Circle(1.0) } else { Rect(1.0, 2.0) }
   |                -----------          ^^^^^^^^^^^^^^ expected `Circle`, found `Rect`
   |                |
   |                expected because of this
   |
help: you could change the return type to be a boxed trait object
   |
13 - fn pick(round: bool) -> impl Shape {
13 + fn pick(round: bool) -> Box<dyn Shape> {
   |
help: if you change the return type to expect trait objects, box the returned expressions
   |
14 |     if round { Box::new(Circle(1.0)) } else { Box::new(Rect(1.0, 2.0)) }
   |                +++++++++           +          +++++++++              +

For more information about this error, try `rustc --explain E0308`.

The error is E0308, and the line that matters is "expected Circle, found Rect". The first branch fixed the hidden type as Circle, so the second branch is a type error. The compiler's suggestion is correct and tells you what the language is asking for: when the type depends on a run-time value (here the round flag), you have left generics behind and need a trait object. Changing the return type to Box<dyn Shape> and boxing each branch is the fix. If the set of types is closed, as it is here, returning the AnyShape enum is the other fix, and it avoids the allocation.

The decision between the two keyword uses is covered in more detail in impl Trait versus dyn Trait.

Trait objects: one function, a vtable, a pointer indirection

A dyn Shape value is a type whose concrete identity has been erased. You cannot hold one directly, because the compiler does not know its size, so it always sits behind a pointer: &dyn Shape, Box<dyn Shape>, Rc<dyn Shape>. The pointer is wide, carrying a second word that points to a vtable, a static table the compiler generated for the pairing of Circle with Shape. The vtable holds the destructor, the size and alignment of the concrete type, and one function pointer per trait method. Calling s.area() loads the pointer from the vtable and calls it. The 16 bytes you saw printed for &dyn Shape are exactly those two words.

There is exactly one compiled copy of total, no matter how many shape types exist, and a new type can be added in a different crate without recompiling this one. That second property is the real reason to use trait objects, and it is one generics only partly match. A plugin system, a handler registry, a set of middleware layers read from a config file: in all of them the concrete types are not known when the calling code compiles. Here is a minimal registry where the list of handlers is chosen at run time from names:

src/main.rsrust
use std::collections::HashMap;

trait Handler {
    fn handle(&self, input: &str) -> String;
}

struct Upper;
struct Count;

impl Handler for Upper {
    fn handle(&self, input: &str) -> String {
        input.to_uppercase()
    }
}
impl Handler for Count {
    fn handle(&self, input: &str) -> String {
        input.chars().count().to_string()
    }
}

fn registry(names: &[&str]) -> HashMap<String, Box<dyn Handler>> {
    let mut map: HashMap<String, Box<dyn Handler>> = HashMap::new();
    for name in names {
        match *name {
            "upper" => map.insert(name.to_string(), Box::new(Upper)),
            "count" => map.insert(name.to_string(), Box::new(Count)),
            _ => None,
        };
    }
    map
}

fn main() {
    // the list comes from a config file in real code, so the types are not known when compiling
    let handlers = registry(&["count", "upper"]);
    for key in ["upper", "count", "missing"] {
        match handlers.get(key) {
            Some(h) => println!("{key}: {}", h.handle("héllo")),
            None => println!("{key}: no such handler"),
        }
    }
}

It prints:

Text
upper: HÉLLO
count: 5
missing: no such handler

The map's value type is Box<dyn Handler>. That single type is what lets a HashMap hold an Upper and a Count side by side, and the function registry builds it from strings, which no generic signature could express. In the match, map.insert(...) returns the previous value as an Option<Box<dyn Handler>>, and the trailing ; after the match discards it. The _ => None arm needs the same type, which is why it is None and not (). The Box::new(Upper) expression has type Box<Upper> and is coerced to Box<dyn Handler> where the context asks for it: that is an unsizing coercion, and it is the one place a concrete type visibly turns into a trait object.

Two details bite in practice. First, a trait object has a lifetime bound that defaults to 'static inside a Box, so Box<dyn Handler> means Box<dyn Handler + 'static> and cannot hold a handler that borrows from a local variable. Write Box<dyn Handler + 'a> if it must. Second, Send and Sync are not implied: sending a boxed handler to another thread requires Box<dyn Handler + Send>, as Send and Sync explained covers. Forgetting that bound gives a long error about threads that points at the trait object.

The other limit is object safety, now called dyn compatibility, which brings up the failing case this guide has been heading towards.

The mistake: a trait that cannot be a trait object

Add a method to Shape that returns a scaled copy of itself, and then try to use the trait as an object:

src/main.rsrust
trait Shape {
    fn area(&self) -> f64;
    fn scaled(&self, k: f64) -> Self;
}

struct Circle(f64);

impl Shape for Circle {
    fn area(&self) -> f64 {
        3.14 * self.0 * self.0
    }
    fn scaled(&self, k: f64) -> Self {
        Circle(self.0 * k)
    }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0))];
    println!("{}", shapes[0].area());
}

The compiler refuses:

Text
error[E0038]: the trait `Shape` is not dyn compatible
  --> src/main.rs:18:29
   |
18 |     let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0))];
   |                             ^^^^^ `Shape` is not dyn compatible
   |
note: for a trait to be dyn compatible it needs to allow building a vtable
      for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
  --> src/main.rs:3:33
   |
 1 | trait Shape {
   |       ----- this trait is not dyn compatible...
 2 |     fn area(&self) -> f64;
 3 |     fn scaled(&self, k: f64) -> Self;
   |                                 ^^^^ ...because method `scaled` references the `Self` type in its return type
   = help: consider moving `scaled` to another trait
   = help: only type `Circle` implements `Shape`; consider using it directly instead.

For more information about this error, try `rustc --explain E0038`.

This is E0038, and the explanation is in the note: a trait must allow building a vtable. A vtable entry is one function pointer with one fixed signature. scaled returns Self, and for a dyn Shape the compiler cannot say how many bytes that return value occupies, since the whole point of the erasure is that it does not know the concrete type. The same applies to a method with a generic type parameter, which would need one vtable entry per instantiation. Associated functions without a self receiver are also out.

The fix is not to give up on the method. It is to tell the compiler that this method is not part of the object, using a where Self: Sized bound. A dyn Shape is not Sized, so the method is simply not callable on one, and is left out of the vtable:

src/main.rsrust
trait Shape {
    fn area(&self) -> f64;
    fn scaled(&self, k: f64) -> Self
    where
        Self: Sized;
}

struct Circle(f64);

impl Shape for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * self.0 * self.0
    }
    fn scaled(&self, k: f64) -> Self {
        Circle(self.0 * k)
    }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Circle(2.0).scaled(0.5))];
    let total: f64 = shapes.iter().map(|s| s.area()).sum();
    println!("{total:.4}");
}

That compiles and prints 6.2832, the sum of a unit circle's area and another circle that was built with radius 2.0 and then scaled by 0.5. Note where scaled is called: on a concrete Circle, before it goes into the box. On the boxed value the method does not exist. If you do need it on the object, the usual pattern is a method that returns Box<dyn Shape> instead, which has a known size. Dyn compatibility lists every rule, and Box<dyn Trait> covers the ownership side.

Enums: the closed world

When you control every type and the list is short, an enum is the best answer and the one newcomers skip because trait objects look more "object oriented". The enum is a single type, so a Vec<AnyShape> holds values inline in one contiguous allocation with no pointer chase. match is exhaustive, so adding a variant makes the compiler list every function that now needs a new arm. And the optimizer sees the whole set of cases, so it can inline each arm and turn the match into a jump table or a branch.

The cost is that the set is closed. A user of your library cannot add a variant, and adding one is a breaking change for anyone who matches on it unless you mark the enum #[non_exhaustive]. Every function that behaves differently by type must be edited when a new type appears, which is the opposite of the trait approach, where the new type brings its own code. This is the old expression problem, and Rust gives you both sides to choose from. The enum dispatch post shows a macro-based way to keep the trait and the enum in step by generating the match for you.

An enum is also as big as its biggest variant. Put a 4 KB array in one variant and every value of the enum, including the unit-like ones, is 4 KB. That is a fine reason to box a rare, large variant, and it is the only size trap here.

What dispatch costs

Everyone quotes "a virtual call is slow" without a number, so here is one. The benchmark builds a million shapes four ways and sums their areas, taking the best of 30 runs per method. The four cases are generic over a single type, dyn over a single type, dyn over an alternating mix of two types, and the enum over the same alternating mix. The setup code (building the vectors, timing with Instant, std::hint::black_box around each input so the optimizer cannot fold the sum away) is routine. The part that differs is three one-line functions, each running the same map and sum over a different collection type:

src/main.rsrust
fn sum_generic<S: Shape>(v: &[S]) -> f64 {
    v.iter().map(|s| s.area()).sum()
}
fn sum_dyn(v: &[Box<dyn Shape>]) -> f64 {
    v.iter().map(|s| s.area()).sum()
}
fn sum_enum(v: &[AnyShape]) -> f64 {
    v.iter().map(|s| s.area()).sum()
}

Built with cargo run --release, the best of 30 runs came out as:

Text
generic, one type          0.95 ms  (sum 40840629)
dyn, one type              0.95 ms  (sum 40840629)
dyn, two types             1.74 ms  (sum 23420342)
enum, two types            0.95 ms  (sum 23420342)

Three things come out of those lines. The cost of the virtual call itself was not visible in the first two rows: dyn over a single type matched the generic version at 0.95 ms for a million elements, which is under a nanosecond each. Both loops are most likely limited by how fast memory streams in, and a correctly predicted indirect branch to the same target costs almost nothing. Second, the penalty appeared when the two types alternated: 1.74 ms, about 80 percent slower than the enum doing the same work. I did not isolate how much of that is the indirect branch and how much is the optimizer being unable to inline, and I do not want to claim a split the measurement did not show. Third, the boxes here were allocated in sequence and sit next to each other in memory. A real collection of trait objects built over a long-running program is scattered across the heap, and each element adds a cache miss that this benchmark did not include. Treat 0.8 ns per call as the floor.

The practical reading is that dispatch cost matters in a loop that touches millions of items per frame or per request, and nowhere else. A handler called once per HTTP request, whose body does a database read, spends its time in the database, and a few nanoseconds of vtable lookup is not visible next to it. Static versus dynamic dispatch goes further into when to measure.

How to choose

QuestionGenericsdyn TraitEnum
Concrete type known when compilingrequirednot neededrequired
Mixed types in one Vecnoyesyes
Others can add types without editing yoursyesyesno
Per-call overheadnone, inlinableindirect call, no inlininga branch, inlinable
Compiled copiesone per type usedoneone
Methods with Self or genericsfineneed where Self: Sizedfine
Memory per element in a Vecexact sizepointer plus a heap allocationsize of largest variant

Work down these questions in order. If the types are decided by data (a config file, a plugin directory, user input), you need dyn Trait, and the choice ends there. If they are decided by the code, ask whether the list is closed and under your control. If yes, and if there are fewer than about ten, use an enum. If the list is open, or large, or every case has a lot of unrelated code, use generics. Default to generics for internal helpers, because they cost nothing you will notice and fail early at compile time.

A compact way to decide, applied to the shapes: an internal geometry library that is only ever called with known shapes should be generic. A drawing program that loads shape plugins should use Box<dyn Shape>. A game with exactly five enemy kinds should use an enum. Same trait, three different right answers.

Associated types and when a trait should be generic

One more design decision sits next to this choice: should a type be a parameter of the trait or an associated type inside it? trait Convert<T> lets one struct implement it many times, once per T. trait Iterator { type Item; } allows exactly one implementation per type, so a caller never has to say which. Use a parameter when a type legitimately has several implementations, as with From, covered in From and Into. Use an associated type when there is one natural answer, and the decision is laid out in associated types versus generic parameters. Associated types also keep trait objects practical, since dyn Iterator<Item = u32> fixes the type at the use site.

When this advice does not apply

Four cases break the defaults above.

First, compile time and binary size outweigh runtime speed. A library that would instantiate a large generic function with dozens of types, or an embedded target with a small flash budget, is often better with one trait-object version of the cold code, even though it is slower. Measure the binary before and after rather than assuming.

Second, the hot path is dominated by something else. If each call does I/O, allocates, or takes a lock, the dispatch cost is lost in the noise and the easiest-to-read option should win. Do not turn clean dyn code into a generic maze for a gain you cannot see.

Third, the benchmark above covers a particular access pattern. Contiguous, same-sized boxes on a modern core with a good branch predictor. With scattered heap objects, a cold cache or a three-way mix of types the gap could be larger. Run your own data through your own loop.

Fourth, this guide leaves out const generics, specialization (still unstable, see specialization) and higher-ranked trait bounds. Those change the shape of the problem rather than the cost. The Rust reference describes trait objects and the dyn compatibility rules formally, and they are the final word when a compiler message is unclear.

In this series

Also inRust
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.