100. std::cmp::Reverse — Sort Descending Without Writing a Closure
Want to sort a Vec in descending order? The old trick is v.sort_by(|a, b| b.cmp(a)), and every time you write it you flip a and b and pray you got it right. std::cmp::Reverse is a one-word replacement.
The closure swap trick
To sort descending, you reverse the comparison. The closure is short but easy to mess up:
| |
Swap the a and b and you silently get ascending order again. Not a bug the compiler can help with.
Enter Reverse
std::cmp::Reverse<T> is a tuple wrapper whose Ord impl is the reverse of T’s. Hand it to sort_by_key and you’re done:
| |
No chance of flipping the comparison the wrong way — the intent is right there in the name.
Sorting by a field, descending
It really shines when you’re sorting structs by a specific field:
| |
Mixing ascending and descending
Sort by one field ascending and another descending? Pack them in a tuple — Reverse composes cleanly:
| |
It works anywhere Ord does
Because Reverse<T> is an Ord type, you can use it with BinaryHeap to turn a max-heap into a min-heap, or with BTreeSet to iterate in reverse order — no extra wrapper types needed.
| |
When to reach for it
Any time you’d write b.cmp(a) — reach for Reverse instead. The code reads top-to-bottom, the intent is obvious, and there’s no comparator to accidentally flip.