Advanced Rust Traits

Traits are Rust's answer to shared behaviour. This post explores generic bounds and dynamic dispatch.

Defining a trait

trait Greet {
    fn greet(&self) -> String;
}

struct Robot;

impl Greet for Robot {
    fn greet(&self) -> String {
        String::from("BEEP BOOP")
    }
}

Static vs dynamic dispatch

Generic bounds are resolved at compile time, while trait objects (dyn Greet) are resolved at runtime.

Generic bounds are monomorphized[1] at compile time, so static dispatch can be faster but produces larger binaries.

  1. Monomorphization generates a specialized copy of a function for each concrete type it is used with.