You can use paired with instead . sort_by Ordering::reversesort_by_key
use std::cmp::Ordering;
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.name()).reverse() {
Ordering::Equal => a.len().cmp(&b.len()),
other => other,
}
});
println!("{:?}", vec);
}
This sorts in reverse alphabetical order, then the links are sorted in ascending order of numbers:
[Foo("beta", 1), Foo("beta", 2), Foo("alpha", 1)]
Starting with Rust 1.17 (via RFC 1677 ), you can write it like this:
vec.sort_by(|a, b| {
a.name().cmp(b.name()).reverse()
.then(a.len().cmp(&b.len()))
});
If you have something that can be denied / inverted, you can simply negate the key .
source
share