|
|
|
|
|
by WakiMiko
2697 days ago
|
|
For sorting sequential fields you can chain comparisons with .then(): struct Date {
year: u32,
month: u32,
day: u32,
}
let mut vec: Vec<Date> = Vec::new();
vec.sort_by(|a,b| {
a.year.cmp(&b.year)
.then(a.month.cmp(&b.month))
.then(a.day.cmp(&b.day))
});
Alternatively you can derive PartialEq, PartialOrd, Eq and Ord for your struct, which will produce a lexicographic ordering based on the top-to-bottom declaration order of the struct's members: #[derive(PartialEq, PartialOrd, Eq, Ord)]
struct Date {
year: u32,
month: u32,
day: u32,
}
|
|
> Alternatively you can derive PartialCmp for your struct, which will produce a lexicographic ordering based on the top-to-bottom declaration order of the struct's members:
Do you mean PartialOrd? partial_cmp is the method. And `sort` requires absolute ordering (Ord) not just partial.