Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::cmp::Ordering;
- #[derive(Debug)]
- struct MyStruct {
- a: usize,
- b: String,
- c: String,
- d: usize,
- }
- enum MyStructKey {
- A,
- B,
- C,
- D,
- }
- impl MyStruct {
- fn cmp_by(&self, other: &Self, keys: &[MyStructKey]) -> Ordering {
- match keys.split_first() {
- Some((MyStructKey::A, tail)) => {
- self.a.cmp(&other.a).then_with(|| self.cmp_by(other, tail))
- }
- Some((MyStructKey::B, tail)) => {
- self.b.cmp(&other.b).then_with(|| self.cmp_by(other, tail))
- }
- Some((MyStructKey::C, tail)) => {
- self.c.cmp(&other.c).then_with(|| self.cmp_by(other, tail))
- }
- Some((MyStructKey::D, tail)) => {
- self.d.cmp(&other.d).then_with(|| self.cmp_by(other, tail))
- }
- None => Ordering::Equal,
- }
- }
- }
- fn main() {
- let a = MyStruct {
- a: 42,
- b: "foo".into(),
- c: "bar".into(),
- d: 314,
- };
- let b = MyStruct {
- a: 271428,
- b: "aaaa".into(),
- c: "bbbb".into(),
- d: 0,
- };
- let c = MyStruct {
- a: 271428,
- b: "aaaa".into(),
- c: "bbbb".into(),
- d: 2,
- };
- let order = &[MyStructKey::B, MyStructKey::A, MyStructKey::C, MyStructKey::D];
- let mut v = vec![a, b, c];
- v.sort_by(|l, r| l.cmp_by(&r, order));
- println!("{:?}", v);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement