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.
Code
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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.