Sub topic 1
Traits and bounds: the starting point
Prerequisites
This chapter assumes basic Rust syntax, ownership, borrowing, structs, traits, generics, and Box.
Traits and bounds
A trait defines behavior that a type can provide. A trait bound restricts a generic type to types that provide that behavior.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn print_area<T: Shape>(shape: &T) {
println!("{}", shape.area());
}
fn main() {
print_area(&Square(3.0));
}Here, T: Shape means that print_area accepts any one concrete type implementing Shape.
Static dispatch with generics
This generic call uses static dispatch. The compiler knows the concrete type and generates specialized machine code for it. This process is called monomorphization. It can be fast because the method call may be inlined, but one function can produce multiple compiled versions.
impl Trait in an argument has similar static-dispatch behavior:
fn print_area(shape: &impl Shape) {
println!("{}", shape.area());
}Each call still uses one concrete type selected at compile time.
What `dyn Trait` means
dyn Shape means a trait object. It represents an unknown concrete type that implements Shape. Unlike a generic parameter, the concrete type is selected at runtime. A trait object is unsized, so Rust cannot store it directly as a local value or as an element in an ordinary Vec.
Putting trait objects behind pointers
Trait objects must normally be placed behind a pointer or reference. Common forms include:
&dyn Shapefor a borrowed trait object.Box<dyn Shape>for an owned, heap-allocated trait object.Rc<dyn Shape>for shared ownership in one thread.Arc<dyn Shape>for shared ownership across threads when the contained type supports the needed bounds.
The pointer provides a known size even though the concrete value does not.
Fat pointers and vtables
A pointer to a trait object is usually a fat pointer. It contains a data pointer and a vtable pointer. The data pointer identifies the value. The vtable contains information and function pointers for that value's concrete implementation.
The extra lookup enables dynamic dispatch. It adds a small runtime cost, but it lets one interface represent different types.
Exercise
Why can Box<dyn Shape> store both a Square and another type implementing Shape?
Show answer
The box has a fixed-size trait-object pointer, while the vtable selects the correct implementation at runtime.