
Understand it
A concrete generic instantiation normally selects the implementation statically and may allow inlining. dyn Trait defers the choice to runtime through a vtable, which permits heterogeneous values behind pointers. The actual cost depends on the workload and optimizer; dynamic dispatch does not itself require a heap allocation. A dyn value has no size the compiler can plan for, so it lives behind a pointer: Box<dyn Trait> is what goes into a Vec.
A trait names behavior that multiple types can provide. Shape::area describes what a caller may ask without assuming how a circle or rectangle stores its dimensions. A generic parameter S: Shape selects a concrete implementation at compile time; a &dyn Shape or Box<dyn Shape> selects through a trait object at runtime. Both use the same trait contract, but they solve different API problems.
Use generics when a function can operate on one concrete type per call and compile-time specialization is useful. Use a trait object when a collection must hold values of several concrete types together or when a choice is only known at runtime. Because concrete types can have different sizes, dyn Shape is unsized and needs a pointer such as &dyn Shape or Box<dyn Shape>. The pointer includes enough information to reach the value and its method table. That indirection has a cost, but it can simplify an extensible design.
Try implementing Shape for two structs, then call both a(&shape) and b(&shape) from the example. Put both shapes into a vector of boxed trait objects and sum their areas. Notice the tradeoff: you can call methods exposed by Shape, but concrete-only methods are not directly available through the trait object. Write the shared contract at the level callers need, and prefer the simpler generic form unless mixed runtime values are a real requirement.
A trait is most useful when it describes a coherent capability, not simply several methods that happen to be near each other. Keep implementations predictable so generic callers can rely on the contract. When a method needs the concrete Self type or a generic parameter, check whether that method should be unavailable through dyn Trait or placed in a separate trait.
Read the code
trait Shape {
fn area(&self) -> f64;
}
// static dispatch, resolved at compile time
fn a<S: Shape>(s: &S) -> f64 { s.area() }
// dynamic dispatch, through a vtable
fn b(s: &dyn Shape) -> f64 { s.area() }The same trait, reached two different ways.
Practice starter
trait Shape { fn area(&self) -> f64; }
struct Circle(f64);
struct Square(f64);
impl Shape for Circle {
fn area(&self) -> f64 { std::f64::consts::PI * self.0 * self.0 }
}
impl Shape for Square {
fn area(&self) -> f64 { self.0 * self.0 }
}
let shapes: ??? = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];Try it
Accept a borrowed Display value and format value= followed by its display representation. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.
What success looks like: The local compiler accepts the changed solution and the separate verification harness finishes all normal and boundary cases. Printing a success message alone does not complete this lab.
Check your understanding
What replaces ??? so one Vec can hold both shapes?
Reveal the answer
- Vec<impl Shape>
- Vec<Box<dyn Shape>>
- Vec<S: Shape>
A trait object erases the concrete type so the elements share one size.
Go deeper
Common misconception: “Vec<impl Shape> can hold a mix of shapes.”
impl Shape stands for one concrete type, and Rust does not accept it in a let type at all. A mix needs Box<dyn Shape>, where every element is one pointer and calls go through a vtable.
- Separate the two calls:
a<S: Shape>(s: &S)is compiled once per concreteS.b(s: &dyn Shape)is compiled once and findsareathrough the vtable. - Predict before checking: Predict whether
a(&shape)andb(&shape)return the same number for one shape. Then predict which of them acceptsshapes[0].as_ref(). - Compare with evidence: Run both: the numbers match.
b(shapes[0].as_ref())compiles, whilea(shapes[0].as_ref())gets E0277, becauseSmust be a sized concrete type.
Transfer challenge: Add a Triangle that implements Shape, push it into shapes, and sum the areas in one loop that names no concrete type. Then give Circle a method of its own and try to call it on shapes[0].
Connections
- Generics: Reusable types and functions
- Lifetimes: Relationships between borrows
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: Traits (courseId "ownership", lessonId "traits") Link: https://crabrix.com/learn/ownership/traits/ Goal: Use generics for static dispatch and trait objects for dynamic dispatch; neither choice alone determines performance. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=ownership/traits) 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.