242. slice::binary_search_by_key — Find a Record by One Field, No Hand-Written Comparator
Binary searching a slice of structs by one field? Don’t hand-roll a .cmp() closure and risk flipping the comparison — project the key and let the stdlib do the rest.
You have a slice sorted by some field and want to find an element by that field. The reflex is binary_search_by with a closure that spells out the comparison — and it’s easy to get the argument order backwards, which silently breaks the search:
| |
binary_search_by_key takes the target and a closure that projects the key. No .cmp(), nothing to get backwards:
| |
On a miss you get Err(i) — the index where the element would go to keep the slice sorted, so you can insert without a second search:
| |
One rule: the slice must already be sorted by the same key you project, otherwise the result is unspecified. When that holds, it’s O(log n) instead of the O(n) scan you’d write by hand.