home ~ socials ~ other projects

Sort a Vec of Structs by Multiple Key Fields in Rust

I'm using Rust's tuples to sort structs by multiple fields.

pub struct Widget {
  first: String,
  second: String,
  third: String
}

impl Widget {
  pub fn new(first: &str, second: &str, third: &str) -> Widget {
    Widget {
      first: first.to_string(),
      second: second.to_string(),
      third: third.to_string(),
    }
  }

  pub fn sort_key(&self) -> (String, String, String) {
    (self.first.to_string(), self.second.to_string(), self.third.to_string())
  }
}

fn main() {
  let mut widgets = vec![
    Widget::new("charlie", "alfa", "bravo"),
    Widget::new("delta", "alfa", "bravo"),
    Widget::new("delta", "bravo", "bravo"),
    Widget::new("alfa", "bravo", "alfa"),
    Widget::new("alfa", "alfa", "alfa"),
    Widget::new("alfa", "alfa", "bravo"),
  ];
  widgets.sort_by_key(|widget| widget.sort_key());

  widgets.iter().for_each(|widget| {
    println!("{} {} {}", widget.first, widget.second, widget.third);
  });
}
Output:
alfa alfa alfa
alfa alfa bravo
alfa bravo alfa
charlie alfa bravo
delta alfa bravo
delta bravo bravo
-- end of line --

References