Sub topic 3
Generics or Trait Objects?
This chapter assumes basic Rust syntax, ownership and borrowing, traits, and Option, Result, and Vec.
Generics or trait objects?
Generics choose a concrete type at compile time. Rust can specialize the code for each type. This is called monomorphization. It usually gives fast static dispatch, but may increase binary size.
A trait object such as Box<dyn Display> stores a value whose concrete type can vary at runtime. Calls use dynamic dispatch through a vtable. This supports mixed collections, with a small runtime cost.
| Choice | Best when | Main trade-off |
|---|---|---|
| `T: Trait` | Types are known by the caller | Fast, but one concrete type per use |
| `dyn Trait` | Values of different types must be combined | Flexible, with allocation or dispatch costs |
Lifetimes next to type parameters
Lifetime parameters and type parameters share the same angle brackets. Lifetimes describe how long references remain valid; type parameters describe data types.
fn longer<'a, T: AsRef<str>>(a: &'a T, b: &'a T) -> &'a T {
if a.as_ref().len() >= b.as_ref().len() { a } else { b }
}
fn main() {
println!("{}", longer(&"rust", &"go"));
}The returned reference cannot outlive either input reference.
Associated types
An associated type lets a trait implementation choose one related type:
trait IteratorLike {
type Item;
fn next_item(&mut self) -> Option<Self::Item>;
}Callers write I: IteratorLike instead of adding another type parameter. Use associated types when each implementing type has one natural associated type.
Blanket implementations
A blanket implementation implements a trait for every type meeting a bound:
impl<T: std::fmt::Debug> Describe for T { /* ... */ }This is convenient, but overlapping implementations are forbidden. A blanket implementation can also apply more broadly than intended.
Const generics
Const generics put values, often array lengths, into types:
fn first<const N: usize>(values: [i32; N]) -> i32 {
values[0]
}
fn main() {
println!("{}", first([4, 8, 15]));
}The compiler knows N during compilation. The function still panics for an empty array, so constraints remain your responsibility.
Default type parameters
A trait or struct can provide a default type:
struct Table<K, V = String> {
key: K,
value: V,
}Table<i32> means Table<i32, String>. Defaults make common cases shorter while preserving customization.
PhantomData and marker types
PhantomData<T> records a type relationship without storing a T. Marker types can prevent invalid combinations, such as adding meters to feet.
use std::marker::PhantomData;
struct Meters;
struct Length<Unit> {
value: f64,
_unit: PhantomData<Unit>,
}
fn main() {
let distance = Length::<Meters> {
value: 3.0,
_unit: PhantomData,
};
println!("{}", distance.value);
}Exercise
When should a design use dyn Trait instead of a generic type parameter?
Show answer
Use dyn Trait when one collection or interface must hold values with different concrete types at runtime.