capypad
0 Tage Serie
rust / intermediate
Snippet

Box<T> für Heap-Allokation und Dynamische Dispatch

Box<T> alloziert Werte auf dem Heap und ermöglicht dynamische Dispatch durch Trait-Objekte mit 'dyn Trait'. Dies erlaubt das Speichern gemischter konkreter Typen in Sammlungen, während Verhalten durch eine gemeinsame Schnittstelle geteilt wird.

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));
}
Erklärung
1
Box::new(Circle {...})
Heap-Allokation - Circle auf Heap gespeichert, Box ist ein Smart Pointer auf dem Stack
2
Box<dyn Drawable>
Trait-Objekt - ermöglicht Laufzeit-Polymorphie für verschiedene Formen
3
&[Box<dyn Drawable>]
Slice von Trait-Objekten - akzeptiert jede Sammlung von drawable Typen
4
s.area()
Virtueller Aufruf, der zur Laufzeit durch vtable aufgelöst wird