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.

RustData Integrity

Code

rustsnippet
23 lines
#[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

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 ->`.