Trait Objects and Dynamic Dispatch

On this page

dyn Trait hides the concrete implementation type behind an agreed interface. It supports heterogeneous implementations and downstream extensions. You can also choose it deliberately to control interfaces and code size when the concrete type is already known at compile time.

Objects Need Not Be on the Heap

&dyn MeasureBorrowed, does not require heap allocationConcrete ValueMay be on the stack, heap, or other valid storageImplementation vtableDynamic method entriestrait object: data and behavior information together determine the callIllustration does not specify vtable field order or slots; its internal layout is not a stable Rust ABI.
trait Measure {
    fn amount(&self) -> usize;
}
impl Measure for usize {
    fn amount(&self) -> usize { *self }
}
impl Measure for String {
    fn amount(&self) -> usize { self.len() }
}
fn total(items: &[&dyn Measure]) -> usize {
    items.iter().map(|item| item.amount()).sum()
}

fn main() {
    let number = 7usize;
    let text = String::from("abc");
    let items: [&dyn Measure; 2] = [&number, &text];
    assert_eq!(total(&items), 10);
}

Here the number and String are local values; &dyn Measure only borrows them. Box<dyn Measure> additionally provides ownership. Dynamic dispatch and heap allocation are separate choices, while String's own byte buffer is a separate storage concern.

A trait object is dynamically sized and is usually accessed through a reference or smart pointer. Its pointer carries a data address and corresponding vtable information; a dynamic call uses the relevant method entry. Trait objects

Do not assume that a particular vtable slot always contains a particular method and cast it manually. Internal fields and destructor entries are not a stable ABI or a cross-compiler-version plugin contract.

Pair the data with its method entry

Observe dispatch through one amount call without treating vtable internals as a stable interface. Here usize returns its value and String returns its byte length. Changing the object changes both data and implementation while the caller still depends only on Measure.

Preparing the visual
Pair the data with its method entry

An object reference retains data and dispatch information; &dyn Trait does not require boxing the object.

Evaluate Dispatch Costs in Context

Dynamic calls generally use indirection and may limit optimization across the call boundary. A compiler with enough implementation information can still devirtualize a call. Generics often enable type-specific optimization, while additional instantiations can increase code size.

An enum's match also selects among alternatives, and its layout may be dominated by its largest variant. Locality, object size, allocations and actual computation can matter more than the presence of a vtable.

Place the Dynamic Boundary Around a Natural Unit of Work

Suppose a parser handles ten thousand bytes. With fn parse(&self, input: &[u8]), one dynamic call can enter a loop that uses concrete types internally. With fn next_byte(&mut self), the caller may cross the dynamic boundary for every byte. Both use dyn, but the potential call counts differ.

This does not mean combining all methods into one giant function. Identify natural units such as a message, batch or rendering operation, then examine the hot path. Also control storage when comparing: Vec<Box<dyn Trait>> may involve per-object allocations and pointer chasing, while an enum array may give every element the space required by its largest variant. These are not all dispatch costs.

Dyn Compatibility: What Can an Erased Type Expose?

Formerly called object safety, dyn compatibility requires that the trait not require Self: Sized, and that its supertraits satisfy the applicable conditions. Associated constants and generic associated types restrict compatibility. Dynamically callable methods cannot have type parameters, depend on unknown Self in ordinary arguments or return values, return opaque impl Trait, or directly be async fn. Lifetime parameters are not the prohibited type parameters. Rules

A method unsuitable for dynamic calls can use where Self: Sized to exclude itself without necessarily excluding the entire trait:

trait Label {
    fn label(&self) -> &str;
    fn duplicate(&self) -> Self where Self: Sized;
}
impl Label for String {
    fn label(&self) -> &str { self }
    fn duplicate(&self) -> Self { self.clone() }
}

fn main() {
    let value = String::from("hello");
    let object: &dyn Label = &value;
    assert_eq!(object.label(), "hello");
    assert_eq!(value.duplicate(), "hello");
    // object.duplicate() is excluded: this method requires a Sized implementation.
}

Ordinary associated types can be specified, as in dyn Iterator<Item = u8>. Clone itself cannot simply become dyn Clone. Any downcasting identifies types; it does not automatically clone objects. Object cloning needs a suitable abstraction, such as a method returning Box.

Fix the Associated Output So the Caller Knows Its Type

Erasing an implementation does not erase every type relationship. These iterators have different internal states but both produce u8. The caller knows next returns Option<u8> and can handle them uniformly.

fn total(input: &mut dyn Iterator<Item = u8>) -> u64 {
    let mut result = 0u64;
    for value in input {
        result += u64::from(value);
    }
    result
}
fn main() {
    let mut range = 1u8..4;
    let mut values = vec![4u8, 5].into_iter();
    assert_eq!(total(&mut range), 6);
    assert_eq!(total(&mut values), 9);
    assert_eq!(range.next(), None);
}

Writing only dyn Iterator omits Item. Specifying dyn Iterator<Item = u8> does not allow an iterator producing String in the same position. The protocol and output type are shared, while implementations differ. As with generics, the u64 sum still needs an overflow policy appropriate to the application.

Ask whether the caller can determine a method's call signature. Returning Self depends on the hidden concrete type, while method type parameters allow many caller-selected instantiations. where Self: Sized retains those methods for concrete-type calls, deliberately exposing only part of the trait through objects; it does not make the excluded methods callable through dyn.

Object Lifetimes and Thread Bounds

In common type positions, Box<dyn Trait> defaults to a 'static object lifetime bound and cannot contain arbitrary short borrows. Use Box<dyn Trait + 'a> when needed. The bound does not require the Box to live until program exit; it restricts the borrows hidden inside it.

Across threads, consider dyn Trait + Send and + Sync explicitly. Erasing a concrete type does not automatically retain all its auto traits. These requirements also interact with whether the outer owner is Box or Arc.

Owning a Container Does Not Mean Owning All Its Data

Box<dyn Text + 'a>Drops the owned objectBorrowed<'a>Stores an &str on the heapString bufferOwned by sourceownsborrowsOwned wrapper, borrowed dataFinish using object before dropping sourceBounds do not copy text or extend source lifetimeOwnership and borrowing shown separately; vtable omitted, not to scale.
trait Text {
    fn text(&self) -> &str;
}
struct Borrowed<'a>(&'a str);
impl Text for Borrowed<'_> {
    fn text(&self) -> &str { self.0 }
}
fn make<'a>(source: &'a str) -> Box<dyn Text + 'a> {
    Box::new(Borrowed(source))
}
fn main() {
    let source = String::from("borrowed text");
    {
        let object = make(&source);
        assert_eq!(object.text(), "borrowed text");
    }
    assert_eq!(source, "borrowed text");
}

Box destroys Borrowed, but Borrowed only borrows source. Borrow checking rejects object escaping source's valid region. Changing the return type to Box<dyn Text> without an appropriate lifetime bound does not promote the borrow to 'static. Having the wrapper own a String is another valid design, with a different ownership relationship.

TypeBounds to distinguish
&'a (dyn Text + 'b)Outer reference lifetime versus bounds on borrows in the hidden implementation
&'a dyn TextThe outer reference usually supplies the object lifetime bound
Box<dyn Text + 'a>Box owns the object, which may contain borrows satisfying 'a
Box<dyn Text>Usually defaults to 'static in unconstrained type positions; local expressions can participate in inference

“dyn defaults to 'static” is too broad. Containing types, trait bounds and expression context affect the rules. Explicit bounds often clarify a borrowed interface. Default object lifetimes

Arc Shares Ownership, Not Arbitrary Thread Safety

Arc<dyn Text + Send + Sync> expresses a thread-shareable interface, but the inserted type must satisfy those bounds. Atomic reference counts do not make RefCell's internal state safe for concurrent shared access. Data access still needs appropriate synchronization. Arc thread safety

Preserve the bounds needed after erasure. A Box<dyn Text> cannot be treated as Box<dyn Text + Send> merely because its original value was String. Send, Sync and 'static address moving across threads, sharing references and restricted borrows respectively; none replaces the others.

Narrow the Interface to a Supertrait

Trait upcasting has been stable since Rust 1.86. A subtrait object can be converted to a supertrait object, allowing a general function to depend on the base interface while extensions remain available to other callers. Rust 1.86

trait Named {
    fn name(&self) -> &str;
}
trait Detailed: Named {
    fn revision(&self) -> u32;
}
struct Document;
impl Named for Document {
    fn name(&self) -> &str { "guide" }
}
impl Detailed for Document {
    fn revision(&self) -> u32 { 3 }
}
fn display(value: &dyn Named) -> String {
    format!("name={}", value.name())
}
fn main() {
    let document = Document;
    let detailed: &dyn Detailed = &document;
    let named: &dyn Named = detailed;
    assert_eq!(detailed.revision(), 3);
    assert_eq!(display(named), "name=guide");
}

This narrows the visible interface; it does not recover Document or authorize the reverse conversion. Directly combining two non-auto traits as dyn Read + Write is invalid. Define a base trait inheriting both and provide suitable implementations instead. An object type may add auto traits such as Send and Sync to one base trait. Object type bounds

Any can support concrete-type identification, but requires 'static and cannot cover arbitrary short-borrowing objects. Frequent downcasts may indicate that required operations are missing from the common trait. Any

Choosing Enum, Generics or Dyn

ApproachWho defines the implementation set?StrengthsCosts to consider
enum + matchThe enum author lists variantsExhaustiveness and centralized state modelingNew variants affect matches and layout
Generic T: TraitThe caller selects TRich type information and specialization opportunitiesInstantiation count and interface complexity
dyn TraitAny implementation satisfying the interfaceHeterogeneity and extensibilityDispatch, lifetimes and dyn compatibility

Ask whether the set is open, whether objects must be owned and whether dynamic calls fit the workload. These questions are more useful than simply asking whether the type is known at compile time. Continue with monomorphization.