Rust Trait Objects
Generics decide the exact type at compile time. Some programs need a list that holds many different types, where the exact type is unknown until the program runs. Trait objects solve that problem. A trait object is like a universal remote: the remote does not care which brand of television it controls, as long as the television understands the standard buttons.
A Shared Behavior
Start with a trait that describes what every shape can do.
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String;
}
struct Circle { radius: f64 }
struct Square { side: f64 }
impl Shape for Circle {
fn area(&self) -> f64 { 3.14159 * self.radius * self.radius }
fn name(&self) -> String { String::from("Circle") }
}
impl Shape for Square {
fn area(&self) -> f64 { self.side * self.side }
fn name(&self) -> String { String::from("Square") }
}The Problem with a Plain Vector
A vector holds one type. A Vec<Circle> rejects squares, and a Vec<Shape> fails because the compiler cannot size an unknown type.
Box<dyn Trait> as the Answer
The keyword dyn marks a trait object. A Box stores each value on the heap and gives every item the same size on the stack: one pointer pair.
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Circle { radius: 2.0 }),
Box::new(Square { side: 3.0 }),
];
for s in shapes.iter() {
println!("{} area: {:.2}", s.name(), s.area());
}
}
Circle area: 12.57 Square area: 9.00
How It Works Inside
A trait object stores two pointers: one to the data and one to a method table, called a vtable. At run time, Rust looks up the right method in the table.
Box<dyn Shape>
+-----------------+
| data pointer |-----> Circle { radius: 2.0 }
| vtable pointer |---+
+-----------------+ |
v
+------------------------+
| area -> Circle::area |
| name -> Circle::name |
+------------------------+
This lookup is called dynamic dispatch.
Static Dispatch Compared with Dynamic Dispatch
| Feature | Generics (static) | Trait objects (dynamic) |
|---|---|---|
| Type known at | Compile time | Run time |
| Speed | Fastest, calls can be inlined | Small lookup cost |
| Mixed types in one list | No | Yes |
| Compiled code size | Larger | Smaller |
Passing Trait Objects to Functions
A reference works as well as a box when ownership is not needed.
fn describe(shape: &dyn Shape) {
println!("{} covers {:.1} square units", shape.name(), shape.area());
}
fn main() {
let c = Circle { radius: 1.0 };
describe(&c);
}Returning Different Types
A function can choose which type to return at run time, as long as the return type is a boxed trait object.
fn make_shape(kind: &str) -> Box<dyn Shape> {
if kind == "circle" {
Box::new(Circle { radius: 1.0 })
} else {
Box::new(Square { side: 1.0 })
}
}Object Safety Rules
Only some traits can become trait objects. The compiler requires that methods avoid features it cannot resolve at run time.
- Methods must not return
Self. - Methods must not have their own generic type parameters.
- The trait must not require
Sized.
The Clone trait breaks the first rule, so Box<dyn Clone> is rejected.
Real-World Uses
- Plugin systems where users add new behaviors
- Graphics programs with many drawable items
- Game characters sharing an
updatemethod - Payment tools that support several providers
Choosing Between Generics and dyn
Pick generics when one concrete type fits each call and speed matters. Pick dyn when a collection must hold different types together or when the type arrives from a decision made while the program runs.
Common Mistakes
Forgetting dyn in modern Rust produces an error. Write Box<dyn Shape> instead of Box<Shape>.
Putting a trait object directly in a vector without a box fails, because the compiler cannot size it. Wrap each item in Box or use a reference.
Using a trait with generic methods or Self returns blocks the conversion. Split the trait into two parts when only some methods need object-safe behavior.
Practice Ideas
- Create an
Animaltrait with aspeakmethod and store a dog, a cat, and a cow in one vector. - Write a payment system where each provider implements a
paymethod.
Key Points
- A trait object hides the concrete type behind a shared trait.
- Use
Box<dyn Trait>for owned values and&dyn Traitfor borrowed ones. - Method calls use a vtable lookup at run time.
- Traits must meet object-safety rules to be used this way.
