Advertisement
Guest User

Untitled

a guest
Aug 25th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. use std::cmp::Ordering;
  2.  
  3. struct MyStruct {
  4. a: usize,
  5. b: String,
  6. c: String,
  7. d: usize,
  8. }
  9.  
  10. enum MyStructKey {
  11. A,
  12. B,
  13. C,
  14. D,
  15. }
  16.  
  17. impl MyStruct {
  18. fn cmp_by(&self, other: &Self, keys: &[MyStructKey]) -> Ordering {
  19. match keys.split_first() {
  20. Some((MyStructKey::A, tail)) => {
  21. self.a.cmp(&other.a).then_with(|| self.cmp_by(other, tail))
  22. }
  23. Some((MyStructKey::B, tail)) => {
  24. self.b.cmp(&other.b).then_with(|| self.cmp_by(other, tail))
  25. }
  26. Some((MyStructKey::C, tail)) => {
  27. self.c.cmp(&other.c).then_with(|| self.cmp_by(other, tail))
  28. }
  29. Some((MyStructKey::D, tail)) => {
  30. self.d.cmp(&other.d).then_with(|| self.cmp_by(other, tail))
  31. }
  32. None => Ordering::Equal,
  33. }
  34. }
  35. }
  36.  
  37. fn main() {
  38. let a = MyStruct {
  39. a: 42,
  40. b: "foo".into(),
  41. c: "bar".into(),
  42. d: 314,
  43. };
  44.  
  45. let b = MyStruct {
  46. a: 271428,
  47. b: "aaaa".into(),
  48. c: "bbbb".into(),
  49. d: 0,
  50. };
  51.  
  52. println!("{:?}", a.cmp_by(&b, &[MyStructKey::A]));
  53. println!("{:?}", a.cmp_by(&b, &[MyStructKey::B]));
  54.  
  55. println!("{:?}", b.cmp_by(&a, &[MyStructKey::A]));
  56. println!("{:?}", b.cmp_by(&a, &[MyStructKey::B]));
  57.  
  58. println!("{:?}", a.cmp_by(&b, &[MyStructKey::A, MyStructKey::B]));
  59. println!("{:?}", a.cmp_by(&b, &[MyStructKey::B, MyStructKey::A]));
  60.  
  61. println!("{:?}", a.cmp_by(&b, &[MyStructKey::B, MyStructKey::A, MyStructKey::C, MyStructKey::D]));
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement