capypad
0 day streak
rust / intermediate
Snippet

Box<T> for Heap Allocation and Dynamic Dispatch

Box<T> allocates values on the heap and enables dynamic dispatch through trait objects with 'dyn Trait'. This allows storing mixed concrete types in collections while sharing behavior through a common interface.

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
trait Drawable {
fn draw(&self);
fn area(&self) -> f64;
}
 
struct Circle { radius: f64 }
struct Square { side: f64 }
 
impl Drawable for Circle {
fn draw(&self) { println!("Drawing circle"); }
fn area(&self) -> f64 { std::f64::consts::PI * self.radius * self.radius }
}
 
impl Drawable for Square {
fn draw(&self) { println!("Drawing square"); }
fn area(&self) -> f64 { self.side * self.side }
}
 
fn total_area(shapes: &[Box<dyn Drawable>]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
 
fn main() {
let shapes: Vec<Box<dyn Drawable>> = vec![
Box::new(Circle { radius: 2.0 }),
Box::new(Square { side: 3.0 }),
];
println!("Total area: {:.2}", total_area(&shapes));
}
Breakdown
1
Box::new(Circle {...})
Heap allocation - Circle stored on heap, Box is a smart pointer on the stack
2
Box<dyn Drawable>
Trait object - enables runtime polymorphism for different shapes
3
&[Box<dyn Drawable>]
Slice of trait objects - accepts any collection of drawable types
4
s.area()
Virtual call resolved at runtime through vtable