Hash And Eq Enable Struct Map Keys

Derive PartialEq, Eq, and Hash on a struct so whole-value lookups work in HashMap, then bucket repeated keys with the entry API.

RustData Integrity

Code

rustsnippet
34 lines
use std::collections::HashMap;

// 结构体作 HashMap 键:需要 PartialEq + Eq + Hash 三件套
#[derive(Debug, PartialEq, Eq, Hash)]
struct Endpoint {
    host: String,
    port: u16,
}

fn main() {
    let mut latency: HashMap<Endpoint, u32> = HashMap::new();
    latency.insert(Endpoint { host: "api.example.com".into(), port: 443 }, 120);
    latency.insert(Endpoint { host: "cdn.example.com".into(), port: 443 }, 30);

    // 查找键只需值相等的临时构造,不必持有原键
    let probe = Endpoint { host: "api.example.com".into(), port: 443 };
    if let Some(ms) = latency.get(&probe) {
        println!("api latency: {ms}ms");
    }

    // 派生的 Hash 按字段逐个写入:字段值相同就是同一个键
    let mut seen: HashMap<Endpoint, usize> = HashMap::new();
    for host in ["api.example.com", "cdn.example.com", "api.example.com"] {
        let key = Endpoint { host: host.into(), port: 443 };
        *seen.entry(key).or_insert(0) += 1;
    }

    // HashMap 遍历顺序不保证:排序后输出才可复现
    let mut counts: Vec<_> = seen.iter().collect();
    counts.sort_by(|a, b| a.0.host.cmp(&b.0.host));
    for (ep, count) in counts {
        println!("{}:{} seen {}x", ep.host, ep.port, count);
    }
}

How it works

Hash And Eq Enable Struct Map Keys comes down to the function main.

Repetition is confined to for host in ["api.example.com", "cdn.example.com", "api.example.com"] — the rest of the file is straight-line.

Putting it to use

The demo output is labeled (api latency:), so every printed line maps back to its originating operation.

Core lines

let mut counts: Vec<_> = seen.iter().collect();
if let Some(ms) = latency.get(&probe) {
    println!("api latency: {ms}ms");
}

Interactive Tools for This Topic

FAQ

What does Hash And Eq Enable Struct Map Keys print when run?
Running the file directly is enough — expect labeled output lines such as `api latency:`.