Skip to main content

Sorting and comparing

`sort` works on anything that implements `Ord`. Floats do not, because `NaN` breaks the rules a total order requires — use `sort_by` with `partial_cmp` for those, and say what you want to happen.

`sort_by_key` is the readable choice when you are sorting by one field. `sort_by` with `Ordering::then` chains tie-breakers.

Deriving `PartialOrd, Ord` on a struct compares fields in declaration order, which is often exactly the sort you wanted.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust