Created
February 8, 2023 15:59
-
-
Save ajitava-git/09786ce76baea8848feb70c75f11655c to your computer and use it in GitHub Desktop.
Implementing PartialEq for a custom type in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
An example of implementing PartialEq for a custom type in Rust | |
*/ | |
#[derive(Debug, PartialEq)] | |
struct Price{ | |
amount: i32, | |
denomination: char | |
} | |
#[derive(Debug, PartialEq)] | |
pub struct Car { | |
name: String, | |
brand: String, | |
car_type: String, | |
price: Price | |
} | |
#[derive(Debug, PartialEq)] | |
pub struct CustomerDetails { | |
city: String, | |
customer_name: String | |
} | |
#[derive(Debug)] | |
pub struct RegisteredCar { | |
car: Car, | |
customer_details: CustomerDetails | |
} | |
impl PartialEq for RegisteredCar { | |
fn eq(&self, other: &Self) -> bool { | |
(self.car == other.car) && (self.customer_details == other.customer_details) | |
} | |
} | |
fn main() { | |
let disney_pixar_husband = Car { | |
name: String::from("Sally Carrera"), | |
brand: String::from("Porsche"), | |
car_type: String::from("Sports"), | |
price: Price{amount: 3, denomination: 'L'} | |
}; | |
let disney_pixar_wife = Car { | |
name: String::from("Lightning McQueen"), | |
brand: String::from("Chevrolet"), | |
car_type: String::from("Sports"), | |
price: Price{amount: 4, denomination: 'L'} | |
}; | |
assert_ne!(disney_pixar_husband, disney_pixar_wife); | |
let speed_racer_villain = Car { | |
name: String::from("Mach 5"), | |
brand: String::from("Ferrari"), | |
car_type: String::from("Race"), | |
price: Price{amount: 3, denomination: 'L'} | |
}; | |
let speed_racer_villain_details = CustomerDetails { | |
city: String::from("Tokyo"), | |
customer_name: String::from("Tatsuo Yoshida") | |
}; | |
let disney_pixar_villain = Car { | |
name: String::from("Chick Hicks"), | |
brand: String::from("Shyster Cremlin"), | |
car_type: String::from("Sports"), | |
price: Price{amount: 4, denomination: 'L'} | |
}; | |
let disney_pixar_villain_details = CustomerDetails { | |
city: String::from("Los Angeles"), | |
customer_name: String::from("Michael Keaton") | |
}; | |
let woody = RegisteredCar { | |
car: speed_racer_villain, | |
customer_details: speed_racer_villain_details | |
}; | |
let jessie = RegisteredCar { | |
car: disney_pixar_villain, | |
customer_details: disney_pixar_villain_details | |
}; | |
assert_eq!(woody,jessie) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment