Binary Search Records By Key
Search a slice sorted by one field with binary_search_by_key, getting either the match index or the insertion point where a new record belongs.
Code
#[derive(Debug)]
struct Deployment {
service: &'static str,
env_order: u32,
}
fn main() {
// binary_search_by_key 要求 records 按同一个键排好序:这里按 env_order 升序
let records = [
Deployment { service: "dev", env_order: 1 },
Deployment { service: "staging", env_order: 3 },
Deployment { service: "prod", env_order: 7 },
];
let hit = records.binary_search_by_key(&3, |d| d.env_order);
println!("order 3 -> {:?}", hit.map(|i| records[i].service));
let miss = records.binary_search_by_key(&4, |d| d.env_order);
println!("order 4 -> {:?}", miss); // Err(2) 表示应插入的位置
let later = records.binary_search_by_key(&7, |d| d.env_order);
println!("order 7 -> {:?}", later.map(|i| records[i].service));
}What the file does
The operative surface is the function main — everything else is wiring.
Caveats
- No dependencies section needed; the standard library is the whole story.
Using it
Signature: fn main()
Output lines are prefixed (order 3 ->, order 4 ->, order 7 ->), so each printed result carries the name of its step.
Key statements
let later = records.binary_search_by_key(&7, |d| d.env_order);
let miss = records.binary_search_by_key(&4, |d| d.env_order);
let hit = records.binary_search_by_key(&3, |d| d.env_order);
Interactive Tools for This Topic
Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
FAQ
- What does Binary Search Records By Key print when run?
- Run it as a complete program — the output lines carry labels such as `order 3 ->`, `order 4 ->`, `order 7 ->`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.