A trait object is a value whose concrete type is erased at compile time and is instead represented by a pointer to a vtable (a table of function pointers) plus a data pointer, allowing different concrete types that implement the same trait to be used interchangeably behind a pointer or reference. In Rust, this is written as dyn Trait (or the older bare trait syntax), and the key requirement is that the trait must be object-safe—meaning it cannot have generic methods, associated constants, or methods that return Self by value, among other restrictions.
Background: Why Trait Objects Exist
Rust’s type system is statically typed and monomorphized: generic functions are compiled separately for each concrete type they are used with. That gives performance but can bloat binary size and prevents storing heterogeneous types in a single collection. Trait objects solve this by providing dynamic dispatch. Instead of the compiler generating a separate copy of a function for every implementor, a trait object carries a pointer to a shared vtable, and method calls go through that table at runtime. This is the same idea as virtual functions in C++ or interfaces in Java, but Rust makes the indirection explicit with the dyn keyword.
The term “trait object” is specific to Rust, though the concept appears in many languages. In Rust, a trait object is not a bare trait; it is always behind a pointer—&dyn Trait, Box<dyn Trait>, Rc<dyn Trait>, and so on. The trait itself is unsized, so you cannot have a local variable of type dyn Trait directly; you must indirect through a reference or smart pointer.
How Trait Objects Work: The Vtable and Fat Pointer
When you create a trait object, the compiler builds a vtable for the concrete type. The vtable contains function pointers for each method of the trait (and its supertraits), plus a pointer to the type’s drop implementation if needed. A trait object reference is a “fat pointer” consisting of two words: one pointer to the data and one pointer to the vtable. Method calls on the trait object load the function pointer from the vtable and call it with the data pointer as the receiver.
- Data pointer: points to the actual value (which may be on the stack or heap).
- Vtable pointer: points to a static table of function pointers specific to the concrete type.
Because the vtable is per-type and static, there is no per-object overhead beyond the two-pointer size. Dynamic dispatch costs an indirect call, which is usually predictable but can inhibit inlining compared to generic monomorphization.
Object Safety: The Rules That Make a Trait Usable as a Trait Object
Not every trait can be turned into a trait object. The trait must be “object-safe.” The exact rules have evolved, but the core restrictions are:
- The trait must not have generic methods (methods with type parameters).
- The trait must not have methods that return
Selfby value (except whereSelf: Sizedis specified). - The trait must not have associated constants.
- The trait must not have associated types without specifying them (e.g.,
dyn Iterator<Item = u8>is allowed because the associated type is fixed). - Methods that take
selfby value are not allowed unlessSelf: Sizedis added. - The trait must not have a
Sizedsupertrait.
If a trait violates these rules, the compiler will reject dyn Trait with an error explaining which method or item makes it non-object-safe. You can often fix this by adding where Self: Sized to the offending method, which excludes it from the vtable and makes the trait object-safe for the remaining methods.
Common Patterns and Examples
A classic example is a trait for drawing shapes:
trait Draw {
fn draw(&self);
}
struct Circle;
struct Square;
impl Draw for Circle { fn draw(&self) { /* ... */ } }
impl Draw for Square { fn draw(&self) { /* ... */ } }
let shapes: Vec<Box<dyn Draw>> = vec![Box::new(Circle), Box::new(Square)];
for s in &shapes { s.draw(); }
Here Box<dyn Draw> is a trait object. The vector holds different concrete types, and draw is dispatched dynamically. Without trait objects, you would need an enum with a variant per shape, or separate vectors per type.
Another common use is error handling: Box<dyn std::error::Error> allows returning different error types from a function. The standard library’s Error trait is object-safe, so this works ergonomically.
Trait Objects vs. Generics: How to Choose
Generics and trait objects are complementary. Generics give static dispatch, monomorphization, and often better performance, but they require knowing the concrete type at compile time and can increase code size. Trait objects give dynamic dispatch, a single compiled version of the code, and the ability to store heterogeneous types, at the cost of an indirect call and a pointer indirection.
- Use generics when performance is critical and the set of types is known at compile time.
- Use trait objects when you need a collection of mixed types, when you want to reduce binary size, or when the concrete type is determined at runtime (e.g., plugin systems).
- You can combine them: a generic function can accept
T: Traitor&dyn Trait; the latter is useful when you want to avoid monomorphizing a large function.
Common Problems and Misconceptions
A frequent mistake is trying to use a trait object where the trait is not object-safe. For example, a trait with a method fn clone_box(&self) -> Box<Self> cannot be made into a trait object because it returns Self. The workaround is to add a separate object-safe method or use a crate like dyn-clone. Another misconception is that dyn Trait is a type you can store directly; it is unsized, so you always need a pointer.
Downcasting is another area of confusion. Rust’s standard library provides Any for runtime type checking, and you can downcast a &dyn Any to a concrete type, but this is not automatic for arbitrary traits. Trait objects do not carry type information beyond the vtable, so you cannot recover the original type without explicit support.
Performance: dynamic dispatch prevents inlining and can hurt in tight loops. However, the overhead is often small compared to the cost of the work inside the method. Profiling is the only way to know for sure.
Frequently Asked Questions
Can any trait be used as a trait object?
No. The trait must be object-safe. Traits with generic methods, associated constants, or methods that return Self by value are not object-safe unless those items are marked where Self: Sized.
What is the difference between dyn Trait and impl Trait?
dyn Trait is a trait object with dynamic dispatch; the concrete type is erased. impl Trait in return position means the function returns some concrete type that implements the trait, but the caller cannot name it; it is still statically dispatched. In argument position, impl Trait is syntactic sugar for a generic parameter.
Why do I need a Box or reference for a trait object?
Because dyn Trait is an unsized type. The compiler does not know its size at compile time, so it cannot be placed on the stack directly. A pointer (reference, Box, Rc, etc.) provides the indirection and carries the vtable pointer.
Can a trait object have multiple traits?
Yes, you can use trait objects with multiple bounds, such as dyn Trait1 + Trait2, as long as only one of them is a non-auto trait (the principal trait) and the others are auto traits like Send or Sync. This is called a trait object with multiple bounds.
Is dynamic dispatch slower than static dispatch?
It can be, because the call goes through a function pointer and cannot be inlined as easily. However, the difference is often negligible for many workloads, and trait objects can reduce code size, which may improve instruction cache usage. Measure before optimizing.
What is the vtable layout?
The vtable is an array of function pointers, one for each method of the trait (and supertraits), plus a pointer to the drop glue and the size and alignment of the concrete type. The exact layout is not stable and should not be relied upon; it is an implementation detail of the compiler.