Polymorphism without inheritance.
Compare enum dispatch, generic dispatch, and trait objects as different design choices.
The idea behind the syntax.
Polymorphism means code can work with values that have different concrete forms. Rust offers several ways to express it. An enum lists a closed set of variants and makes each case visible to match. A generic function accepts any type meeting its bounds and is resolved at compile time. A trait object such as &dyn Draw hides a concrete type behind a shared interface and selects the implementation at runtime.
These tools solve different problems. An enum is strong when you control every variant and want exhaustive decisions. A generic is strong when callers know their concrete type but the algorithm needs only a capability. A trait object is useful when a single collection must hold different concrete types behind one behavior. No one form replaces the others; the right choice follows from whether the set of types is open or closed and whether runtime heterogeneity matters.
What Rust is checking.
A trait object is a wide pointer that carries access to data and a method table for the relevant trait implementation. Dynamic dispatch has a small runtime cost and limits some optimisations, but it can simplify an open-ended interface. Not every trait can become a trait object; object-safety rules ensure methods can be called without knowing the hidden concrete type.
Rust does not have classical inheritance for sharing fields and methods through a parent class. Composition puts reusable values inside a struct; traits share behavior contracts. This can lead to a clearer separation between what a value contains and what it can do. The code examples make the dispatch choice concrete. Read them with one question in mind: who chooses the set of possible types, the library author or the caller?
See the rule in context.
Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.
Trait objects & dynamic dispatch
A trait object such as &dyn Trait or Box<dyn Trait> hides a concrete type behind a dynamic dispatch interface. This differs from generic static dispatch and is useful for heterogeneous collections or runtime-selected implementations. Not every trait is dyn-compatible: methods requiring arbitrary generic type parameters or returning an unconstrained Self can prevent object use. Use dynamic dispatch when the flexibility is valuable, not just to avoid understanding the concrete ownership model.
trait Render {
fn render(&self) -> String;
}
struct Heading;
struct Divider;
impl Render for Heading {
fn render(&self) -> String {
"BUILD LAB".into()
}
}
impl Render for Divider {
fn render(&self) -> String {
"---------".into()
}
}
fn main() {
let blocks: Vec<Box<dyn Render>> = vec![Box::new(Heading), Box::new(Divider)];
for block in blocks {
println!("{}", block.render());
}
}BUILD LAB ---------
- Each Box owns one concrete value.
- dyn Render permits different implementations in one vector.
- Calling render dispatches through the trait object.
The boundary: Box<dyn Trait> usually implies owned allocation and dynamic dispatch. Borrow &dyn Trait when independent ownership is unnecessary.
Enums & data-bearing variants
An enum describes one of several variants, and each variant can carry a different data shape. This is useful for states such as queued, running with a worker ID, or failed with a message. A pair of booleans could express contradictory combinations; an enum can make those states unrepresentable. Pattern matching inspects the variant and binds its data. Derive traits only when their behavior fits the data, and prefer domain types to magic strings for closed sets of choices.
enum Job {
Queued,
Running { worker: u32 },
Failed(String),
}
fn describe(job: Job) -> String {
match job {
Job::Queued => "queued".into(),
Job::Running { worker } => format!("worker {worker}"),
Job::Failed(reason) => format!("failed: {reason}"),
}
}
fn main() {
println!("{}", describe(Job::Running { worker: 7 }));
assert_eq!(describe(Job::Queued), "queued");
assert_eq!(describe(Job::Failed("offline".into())), "failed: offline");
}worker 7
- Running carries a named worker field.
- Failed owns its message.
- The match handles every variant.
The boundary: Do not hide a useful domain enum behind arbitrary strings if callers need exhaustive checks.
Generics & type parameters
A generic parameter stands for a type chosen by the caller or inferred from usage. The function body still has to be valid for its declared bounds. Rust normally monomorphizes generic functions into concrete versions used by the program, so generic code does not automatically imply dynamic dispatch. Start with the operations the algorithm needs and express those as bounds. Prefer a small clear generic function over a highly abstract signature that makes everyday calls hard to understand.
fn first<T>(values: &[T]) -> Option<&T> {
values.first()
}
fn main() {
println!("{:?}", first(&[3, 5]));
println!("{:?}", first(&["Rust", "Python"]));
}Some(3)
Some("Rust")- T is inferred separately at the two calls.
- The function borrows any element type.
- No Copy bound is necessary because it returns a reference.
The boundary: A generic T does not automatically support addition, comparison, formatting, or cloning. Declare only the capabilities required.
Keep this model.
Enums close the set of alternatives, generics preserve concrete types, and trait objects erase a type behind a capability. Choose from the shape of the problem.