Sub topic 2
Static dispatch with generics
This chapter covers how Rust compiles generic code that calls trait methods, and what that costs and gains. It assumes you can write structs, implement traits, and read a trait bound such as T: Display. It also assumes you know basic ownership and borrowing. Trait objects are not covered here. This chapter sets up the baseline that they are later compared against.
Generic functions and trait bounds
A generic function takes a type parameter, and a trait bound limits which types are accepted. Inside the function you may call only what the bound promises.
trait Shape {
fn area(&self) -> f64;
}
struct Circle {
r: f64,
}
struct Rect {
w: f64,
h: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.r * self.r
}
}
impl Shape for Rect {
fn area(&self) -> f64 {
self.w * self.h
}
}
fn print_area<T: Shape>(s: &T) {
println!("{:.2}", s.area());
}
fn main() {
print_area(&Circle { r: 1.0 });
print_area(&Rect { w: 2.0, h: 3.0 });
}This prints 3.14 and then 6.00. The caller never names T. The compiler infers it from the argument: Circle in the first call and Rect in the second.
When bounds get long, move them into a where clause. The two forms mean the same thing.
use std::fmt::Display;
fn join_all<T>(items: &[T]) -> String
where
T: Display,
{
items
.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>()
.join(", ")
}
fn main() {
println!("{}", join_all(&[1, 2, 3]));
println!("{}", join_all(&["a", "b"]));
}The output is 1, 2, 3 and then a, b.
What the compiler does: monomorphization
Rust compiles generic code by monomorphization. For each distinct concrete type a generic function is used with, the compiler generates a separate, specialized copy of the function. It does this at compile time. In the example above, the compiled program contains something equivalent to two functions:
print_areawithT = Circleprint_areawithT = Rect
In each copy, the call s.area() is a direct call to one known function. The compiler picks the target while compiling, so this is called static dispatch. Dispatch is the step of deciding which function body runs for a method call.
Because each copy knows its exact type, the optimizer can inline area into the caller, remove dead branches, and keep values in registers. This is why iterator chains and generic collections in Rust usually compile to code as fast as a hand-written loop.
Three ways to write the same bound
Rust offers several equivalent spellings for a bounded parameter.
trait Shape {
fn area(&self) -> f64;
}
struct Circle(f64);
impl Shape for Circle {
fn area(&self) -> f64 {
3.0 * self.0 * self.0
}
}
// 1. Named type parameter with an inline bound.
fn a<T: Shape>(s: &T) -> f64 {
s.area()
}
// 2. Named type parameter with a where clause.
fn b<T>(s: &T) -> f64
where
T: Shape,
{
s.area()
}
// 3. impl Trait in argument position: an anonymous type parameter.
fn c(s: &impl Shape) -> f64 {
s.area()
}
fn main() {
let x = Circle(2.0);
println!("{} {} {}", a(&x), b(&x), c(&x));
}This prints 12 12 12. All three monomorphize identically. The difference is in what you can express.
| Feature | `fn f<T: Shape>` | `fn f(x: &impl Shape)` |
|---|---|---|
| Name the type inside the body | Yes, as `T` | No |
| Force two arguments to be the same type | Yes | No, each `impl` is independent |
| Caller picks type with turbofish `f::<Circle>(..)` | Yes | No (allowed only in newer compilers when all params are explicit) |
The second row matters in practice. Consider these two signatures:
trait Shape {
fn area(&self) -> f64;
}
struct Circle(f64);
struct Rect(f64, f64);
impl Shape for Circle {
fn area(&self) -> f64 {
3.0 * self.0 * self.0
}
}
impl Shape for Rect {
fn area(&self) -> f64 {
self.0 * self.1
}
}
fn total_same<T: Shape>(a: &T, b: &T) -> f64 {
a.area() + b.area()
}
fn total_mixed(a: &impl Shape, b: &impl Shape) -> f64 {
a.area() + b.area()
}
fn main() {
println!("{}", total_same(&Circle(1.0), &Circle(2.0)));
println!("{}", total_mixed(&Circle(1.0), &Rect(2.0, 3.0)));
}The output is 15 and then 9. Calling total_same(&Circle(1.0), &Rect(2.0, 3.0)) is a compile error, because T would have to be both Circle and Rect. The mixed version compiles one copy for each pair of types it is called with.
Returning impl Trait
impl Trait is also allowed as a return type. It means "one specific concrete type that implements this trait, and I am not going to name it."
fn evens(limit: u32) -> impl Iterator<Item = u32> {
(0..limit).filter(|n| n % 2 == 0)
}
fn main() {
let v: Vec<u32> = evens(10).collect();
println!("{:?}", v);
}This prints [0, 2, 4, 6, 8]. The real return type is Filter<Range<u32>, {closure}>. A closure's type has no name you can write, so impl Iterator is the only practical way to return it without boxing.
The word "one" is the important part. The function body must return the same concrete type on every path. The compiler decides the type when it compiles the function, not when the program runs. A function that returns a Circle in one if branch and a Rect in the other is rejected with a "mismatched types" error, even though both implement Shape. The same rule explains why vec![Circle(1.0), Rect(2.0, 3.0)] does not compile when you want a Vec of shapes. A Vec<T> holds exactly one T.
Costs and benefits
Static dispatch trades compile-time and binary size for run-time speed.
- Benefit: calls are direct, so they can be inlined and optimized across the call boundary.
- Benefit: there is no pointer indirection and no extra data stored with each value.
- Benefit: the full type is known, so you can use
Copy, returnSelf, call generic methods, and use associated types freely. - Cost: each instantiation is compiled separately. Heavy generic use with many types increases compile time and binary size (code bloat).
- Cost: every value is one concrete type. You cannot put different types in one
Vec<T>or pick between types at run time. - Cost: generic functions in a library must expose their bounds, and the source must be available to compile each instantiation, which is why generic code lives in the crate's public API as source-level detail.
Edge cases to know
Every generic parameter has an implicit Sized bound. fn print_area<T: Shape>(s: &T) therefore accepts only types whose size is known at compile time. It rejects unsized types such as str, [u8], and dyn Shape. To accept those, write T: Shape + ?Sized, which relaxes the implicit bound. You will need this when generic code must also work with trait objects, which a later chapter covers.
The inner-function technique looks like this:
use std::path::Path;
fn read_len<P: AsRef<Path>>(path: P) -> std::io::Result<usize> {
fn inner(path: &Path) -> std::io::Result<usize> {
Ok(std::fs::read(path)?.len())
}
inner(path.as_ref())
}
fn main() {
match read_len("does-not-exist.txt") {
Ok(n) => println!("{} bytes", n),
Err(e) => println!("error: {}", e.kind()),
}
}If the file is missing, this prints error: entity not found. Only the one-line wrapper is copied for each P. The inner function is compiled once.
Common errors
the trait bound X: Shape is not satisfied: the type you passed has noimpl Shape for X. Add the impl or pass a different type.no method named area found for type parameter T: you used a method the bounds do not promise. AddT: Shape.mismatched typeson a returnedimpl Trait: your function returns more than one concrete type. Return one type, or use a different tool for runtime choice, which is the subject of the next chapters.type annotations needed: the compiler cannot inferT, for example withcollect()orparse(). Annotate with a turbofish likeparse::<u32>()or a typedlet.
Exercise
A function is declared as fn pair_area<T: Shape>(a: &T, b: &T) -> f64. Why does pair_area(&Circle(1.0), &Rect(2.0, 3.0)) fail to compile, and how would you change the signature so it compiles while still using static dispatch? How many copies of the function does the compiler generate for your fix if the function is called with the type pairs (Circle, Rect) and (Rect, Circle)?
Show answer
Both parameters share one type parameter T, so the arguments must have the same concrete type, and Circle and Rect differ. Declare two parameters, either fn pair_area<A: Shape, B: Shape>(a: &A, b: &B) or fn pair_area(a: &impl Shape, b: &impl Shape). Monomorphization creates one copy per distinct combination of types, so the two pairs (Circle, Rect) and (Rect, Circle) produce two copies.