74. slice::is_sorted — Ask the Slice if It's Already Sorted
You’ve written windows(2).all(|w| w[0] <= w[1]) one too many times. The is_sorted family of methods says what you actually mean — in one call.
Checking whether data is already in order used to mean rolling your own predicate:
| |
It works, but you have to remember windows(2), get the comparison direction right, and hope the next reader recognizes the pattern.
Now there’s a method that does exactly this:
| |
Empty slices and single-element slices are considered sorted — no edge-case surprises:
| |
Need a custom comparator? is_sorted_by takes a closure over pairs of references and returns bool:
| |
And is_sorted_by_key extracts a key first — perfect for structs:
| |
A practical use: skip sorting when the data is already ordered:
| |
Available on slices and by extension on Vec, arrays, and anything that derefs to [T]. Stabilized in Rust 1.82 — no crate needed.