SHARE
TWEET

Untitled

a guest Aug 25th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::cmp::Ordering;
  2.  
  3. #[derive(Debug)]
  4. struct MyStruct {
  5.     a: usize,
  6.     b: String,
  7.     c: String,
  8.     d: usize,
  9. }
  10.  
  11. enum MyStructKey {
  12.     A,
  13.     B,
  14.     C,
  15.     D,
  16. }
  17.  
  18. impl MyStruct {
  19.     fn cmp_by(&self, other: &Self, keys: &[MyStructKey]) -> Ordering {
  20.         match keys.split_first() {
  21.             Some((MyStructKey::A, tail)) => {
  22.                 self.a.cmp(&other.a).then_with(|| self.cmp_by(other, tail))
  23.             }
  24.             Some((MyStructKey::B, tail)) => {
  25.                 self.b.cmp(&other.b).then_with(|| self.cmp_by(other, tail))
  26.             }
  27.             Some((MyStructKey::C, tail)) => {
  28.                 self.c.cmp(&other.c).then_with(|| self.cmp_by(other, tail))
  29.             }
  30.             Some((MyStructKey::D, tail)) => {
  31.                 self.d.cmp(&other.d).then_with(|| self.cmp_by(other, tail))
  32.             }
  33.             None => Ordering::Equal,
  34.         }
  35.     }
  36. }
  37.  
  38. fn main() {
  39.     let a = MyStruct {
  40.         a: 42,
  41.         b: "foo".into(),
  42.         c: "bar".into(),
  43.         d: 314,
  44.     };
  45.    
  46.     let b = MyStruct {
  47.         a: 271428,
  48.         b: "aaaa".into(),
  49.         c: "bbbb".into(),
  50.         d: 0,
  51.     };
  52.    
  53.     let c = MyStruct {
  54.         a: 271428,
  55.         b: "aaaa".into(),
  56.         c: "bbbb".into(),
  57.         d: 2,
  58.     };
  59.  
  60.     let order = &[MyStructKey::B, MyStructKey::A, MyStructKey::C, MyStructKey::D];
  61.     let mut v = vec![a, b, c];
  62.     v.sort_by(|l, r| l.cmp_by(&r, order));
  63.    
  64.     println!("{:?}", v);
  65. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top