trait Material {
fn get_cost(&self) -> f64;
}
#[derive(Debug)]
struct Carpet {
area: f64
}
#[derive(Debug)]
struct Tile {
area: f64
}
#[derive(Debug)]
struct Wood {
area: f64
}
impl Material for Carpet {
fn get_cost(&self) -> f64 {
self.area * 10.0
}
}
impl Material for Tile {
fn get_cost(&self) -> f64 {
self.area * 15.0
}
}
impl Material for Wood {
fn get_cost(&self) -> f64 {
self.area * 20.0
}
}
fn main() {
let v: Vec<&dyn Material> = vec![
&Carpet { area: 1.1 },
&Tile { area: 2.5 },
&Wood {area: 3.1}
];
let mut total_cost = 0.0;
for item in v {
total_cost += item.get_cost();
}
println!("Total cost: {}", total_cost);
}
Vec
need some kind of indirection to contain trait objects, but what kind exactly - depends on the use-case: whether do you need exclusively-owned Box<dyn Trait>
, shared-owned Arc<dyn Trait>
, exclusively-borrowed &mut dyn Trait
or shared-borrowed &dyn Trait
, it's possible to create a Vec
of each one. It's only impossible to have a bare Vec<dyn Trait>
.
4 Likes
Thanks, makes it clear for me.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.