#170
May 2026
170. Ordering::then_with — Chain Comparators for Multi-Key Sorts
Sorting by name, then by age, then by id ends in a nested if a == b { ... } ladder. Ordering::then_with flattens the whole thing into one expression.
The pain: a manual tie-break ladder grows ugly fast.
| |
Ordering has two combinators built for exactly this:
then(other)— eager: returnsselfif it’s notEqual, otherwiseother.then_with(|| other)— lazy: only computes the next comparison if the previous wasEqual.
Prefer then_with whenever the next cmp does real work (string comparison, derived keys), so you don’t pay for it on every pair.
| |
Reads top-to-bottom in priority order, no nesting, no early-return. Mixing ascending and descending is a one-character change — wrap a field in Reverse:
| |
The same pattern works in any Ord/PartialOrd impl — then_with is how a hand-written cmp stays readable.