Heap
Box
Using Box is a smart pointer that provides ownership for heap-allocated data in Rust. This is useful for large data structures or when the size of the data is not known at compile time. This is often used for recursive data structures and dynamic dispatch which is essential for polymorphism.
trait Shape { fn area(&self) -> f64; } struct Circle { radius: f64, } impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.radius * self.radius } } // Function that takes a Box<dyn Shape> to allow for dynamic dispatch fn print_area(shape: Box<dyn Shape>) { println!("The area is {}", shape.area()); } fn main() { let circle = Circle { radius: 5.0 }; let boxed_circle: Box<dyn Shape> = Box::new(circle); print_area(boxed_circle); }