实现说明
Hash 与 Eq 让结构体作 map 键以函数 main为骨架。
在这里做循环的是 for host in ["api.example.com", "cdn.example.com", "api.example.com"]。
使用要点
- 直接运行文件,输出会带上标签,比如
api latency:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「Hash 与 Eq 让结构体作 map 键」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 api latency: 这类标签。
核心语句
let mut counts: Vec<_> = seen.iter().collect();
if let Some(ms) = latency.get(&probe) {
println!("api latency: {ms}ms");
}
代码示例
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);
}
}