Guest User

Untitled

a guest
Dec 11th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. use std::collections::HashSet;
  2. use std::hash::{Hash, Hasher};
  3. use std::borrow::Borrow;
  4.  
  5. #[derive(Debug)]
  6. struct Record {
  7. id: String,
  8. data: String,
  9. }
  10.  
  11. impl Record {
  12. fn get_key(&self) -> &str {
  13. &self.id
  14. }
  15.  
  16. #[allow(dead_code)]
  17. // required because == will only check get_key()
  18. fn identical(&self, other: &Record) -> bool {
  19. self.id == other.id && self.data == other.data
  20. }
  21. }
  22.  
  23. impl Hash for Record {
  24. fn hash<H: Hasher>(&self, state: &mut H) {
  25. self.get_key().hash(state);
  26. }
  27. }
  28.  
  29. impl PartialEq for Record {
  30. fn eq(&self, r: &Record) -> bool {
  31. self.get_key().eq(r.get_key())
  32. }
  33. }
  34.  
  35. impl Eq for Record {}
  36.  
  37. impl Borrow<str> for Record {
  38. fn borrow(&self) -> &str {
  39. self.get_key()
  40. }
  41. }
  42.  
  43. fn main() {
  44. let a = Record { id: "a".into(), data: "A".into() };
  45. let b = Record { id: "b".into(), data: "B".into() };
  46. let c = Record { id: "c".into(), data: "A".into() };
  47.  
  48. let mut h : HashSet<Record> = HashSet::new();
  49. h.insert(a);
  50. h.insert(b);
  51. h.insert(c);
  52.  
  53. let ra = h.get("a");
  54. println!("{:?}", ra);
  55. }
Add Comment
Please, Sign In to add comment