genericstraitsdispatch

dyn Trait where impl Trait or generics fit

Reaching for Box<dyn Trait> by reflex when a static-dispatched parameter would do.

Why this looks tempting

dyn lets you store mixed types in one Vec, and the type signature shrinks.

Why wrong

dyn Trait adds a vtable, indirection, and an allocation (when boxed). The compiler loses the ability to inline and monomorphize. For single-call sites that's pure overhead; for hot paths it's a measurable regression.

Fix

Use generics or impl Trait for parameters and return types when the type is known at the call site. Reach for dyn only when you must store heterogeneous values together (Vec<Box<dyn Trait>>) or break compile-time cycles.

Canonical alternative

trait-system/trait-objects