Reverse specific key when sorting with multiple keys
问题 When sorting with multiple keys, how can I reverse the order of an individual key? For example: vec.sort_by_key(|k| (foo(k).reverse(), bar(k))); 回答1: You can use sort_by paired with Ordering::reverse instead of sort_by_key . use std::cmp::Ordering; #[derive(Debug)] struct Foo(&'static str, u8); impl Foo { fn name(&self) -> &str { self.0 } fn len(&self) -> u8 { self.1 } } fn main() { let mut vec = vec![Foo("alpha", 1), Foo("beta", 2), Foo("beta", 1)]; vec.sort_by(|a, b| { match a.name().cmp(b