Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashSet;
- use std::hash::{Hash, Hasher};
- use std::borrow::Borrow;
- #[derive(Debug)]
- struct Record {
- id: String,
- data: String,
- }
- impl Record {
- fn get_key(&self) -> &str {
- &self.id
- }
- #[allow(dead_code)]
- // required because == will only check get_key()
- fn identical(&self, other: &Record) -> bool {
- self.id == other.id && self.data == other.data
- }
- }
- impl Hash for Record {
- fn hash<H: Hasher>(&self, state: &mut H) {
- self.get_key().hash(state);
- }
- }
- impl PartialEq for Record {
- fn eq(&self, r: &Record) -> bool {
- self.get_key().eq(r.get_key())
- }
- }
- impl Eq for Record {}
- impl Borrow<str> for Record {
- fn borrow(&self) -> &str {
- self.get_key()
- }
- }
- fn main() {
- let a = Record { id: "a".into(), data: "A".into() };
- let b = Record { id: "b".into(), data: "B".into() };
- let c = Record { id: "c".into(), data: "A".into() };
- let mut h : HashSet<Record> = HashSet::new();
- h.insert(a);
- h.insert(b);
- h.insert(c);
- let ra = h.get("a");
- println!("{:?}", ra);
- }
Add Comment
Please, Sign In to add comment