capypad
0 day streak
rust / intermediate
Snippet

Trait Objects and Dynamic Dispatch

Trait objects enable dynamic dispatch, allowing you to work with values of different types through a common interface. The `dyn Trait` syntax creates a runtime-polymorphic reference. This comes with a small performance cost (vtable lookup) but provides flexibility that static dispatch cannot achieve.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
trait Drawable {
fn draw(&self);
fn area(&self) -> f64;
}
 
struct Circle {
radius: f64,
}
 
struct Rectangle {
width: f64,
height: f64,
}
 
impl Drawable for Circle {
fn draw(&self) {
println!("Drawing a circle with radius {}", self.radius);
}
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
 
impl Drawable for Rectangle {
fn draw(&self) {
println!("Drawing a rectangle {}x{}", self.width, self.height);
}
fn area(&self) -> f64 {
self.width * self.height
}
}
 
fn render_all(drawables: Vec<&dyn Drawable>) {
for d in drawables {
d.draw();
}
}
 
fn main() {
let shapes: Vec<&dyn Drawable> = vec![
&Circle { radius: 2.0 },
&Rectangle { width: 3.0, height: 4.0 },
];
 
render_all(shapes);
 
let total_area: f64 = shapes.iter().map(|s| s.area()).sum();
println!("Total area: {}", total_area);
}
Breakdown
1
Vec<&dyn Drawable>
A vector of trait objects - each holds a reference to any type implementing Drawable
2
fn draw(&self)
Method signature in trait - &self enables dynamic dispatch
3
dyn Drawable
Dynamic dispatch marker - Rust uses a vtable at runtime to resolve method calls