Trait objects

Contents

Trait objects#

&dyn Trait or Box<dyn Trait> is a runtime-dispatched reference to anything implementing Trait. Pay a vtable indirection in exchange for dynamic polymorphism.

Define a trait.

trait Listener { fn on_msg(&self, msg: &str); }

Hold a vector of boxed listeners and dispatch dynamically.

fn dispatch(listeners: &[Box<dyn Listener>], msg: &str) {
    for l in listeners { l.on_msg(msg); }
}

For static dispatch (no vtable), use impl Trait or generic parameters.

fn dispatch_static<L: Listener>(listener: &L, msg: &str) {
    listener.on_msg(msg);
}

References#

  • OOP for trait declarations and impl blocks.

  • Generics for the static-dispatch alternative.