Original: Comparison on a `Box<(dyn Valueable + 'static)>` fails - #6 by canina
Current code:
Updated
use std::cmp::Ordering;
#[derive(Clone)]
struct Painting {
artist: String,
title: String,
current_price: f32,
}
#[derive(Clone)]
struct Car {
brand: String,
model: String,
original_price: f32,
age: u8,
}
pub trait Valueable {
fn price(&self) -> f32;
fn description(&self) -> String;
}
impl Valueable for Car {
fn price(&self) -> f32 {
return self.original_price * 0.95_f32.powf(self.age.into());
}
fn description(&self) -> String {
let mut description = String::new();
description.push_str(&self.brand);
description.push_str(", ");
description.push_str(&self.model);
description.push_str(", ");
description.push_str(&self.price().to_string());
description.push_str(", ");
description.push_str(&self.age.to_string());
return description;
}
}
impl Valueable for Painting {
fn price(&self) -> f32 {
return self.current_price;
}
fn description(&self) -> String {
let mut description = String::new();
description.push_str(&self.artist);
description.push_str(", ");
description.push_str(&self.title);
description.push_str(", ");
description.push_str(&self.current_price.to_string());
return description;
}
}
pub enum BST {
Leaf {
value: Box<dyn Valueable>,
left: Box<BST>,
right: Box<BST>,
},
Empty,
}
impl BST {
pub fn new() -> Self {
BST::Empty
}
pub fn add(&mut self, new_value: Box<dyn Valueable>) {
match self {
BST::Leaf {
value,
left,
right,
} => match new_value.price().partial_cmp(&value.price() ) {
Some(Ordering::Less) => left.add(new_value),
Some(Ordering::Greater) => right.add(new_value),
Some(Ordering::Equal) => return,
None => panic!("At least one price is NaN"),
},
BST::Empty => {
*self = BST::Leaf {
value: new_value,
left: Box::new(BST::Empty),
right: Box::new(BST::Empty),
}
}
}
}
pub fn contains(&self, find_value: Box<dyn Valueable>) -> bool {
match self {
BST::Leaf {
value,
left,
right,
} => match find_value.price().total_cmp(&value.price()) {
Ordering::Less => left.contains(find_value),
Ordering::Greater => right.contains(find_value),
Ordering::Equal => true,
},
BST::Empty => false,
}
}
pub fn as_vector(&mut self) -> Vec::<String> {
match self {
BST::Empty => return Vec::new(),
BST::Leaf { value, left ,right } => {
let mut values = right.as_vector();
values.push(value.description());
values.extend(left.as_vector());
values
},
}
}
}
fn main(){
let mut bst = BST::new();
let car1 = Car {
brand: "Brand".to_string(),
model: "model".to_string(),
original_price: 100000.75,
age: 3,
};
BST::add(&mut bst, Box::new(car1.clone()));
let painting1 = Painting {
artist: "Artist".to_string(),
title: "Title".to_string(),
current_price: 100.50,
};
BST::add(&mut bst, Box::new(painting1));
println!("{:?}", BST::contains(&mut bst, Box::new(car1.clone())));
println!("{:?}", BST::as_vector(&mut bst));
}
I will link code in full from no on, thank you for reminding me.