← 中文资源

简体中文版本

用 entry or_insert_with 与借用查找避免多余分配

在 HashMap<String, V> 上先用 &str 借用调用 get_mut 命中分支,未命中时再经 entry 与 or_insert_with_key 惰性初始化键值对。

阅读英文原文

实现说明

用 entry or_insert_with 与借用查找避免多余分配可以归结为函数 record_hit、main。 for key in ["auth", "billing", "auth", "auth", "search", "billing"] 反复执行,循环体之外没有别的重复。

使用要点

  • 只用内建 API,全无多余待核验的第三方包供应链。
  • 跑完文件,输出里会留下标记——key=、total unique buckets=、sample label:。
  • main 按顺序串起 record_hit;运行文件就会把这个流程跑一遍。

常见问题

运行「用 entry or_insert_with 与借用查找避免多余分配」会打印什么?

运行文件本身,key=、total unique buckets=、sample label: 这些前缀各对应一段演示逻辑。

入口签名:fn record_hit(buckets: &mut HashMap<String, Bucket>, key: &str, builds: &mut u32) -> u32

核心语句

if let Some(existing) = buckets.get_mut(key) {
    existing.hits += 1;
    existing.hits
} else {
    let entry = buckets.entry(key.to_owned()).or_insert_with_key(|owned_key| {
        *builds += 1;
        Bucket { label: format!("bucket:{owned_key}"), hits: 0 }
    });
    entry.hits += 1;
    entry.hits
}

代码示例

use std::collections::HashMap;

#[derive(Debug)]
struct Bucket {
    label: String,
    hits: u32,
}

fn record_hit(buckets: &mut HashMap<String, Bucket>, key: &str, builds: &mut u32) -> u32 {
    if let Some(existing) = buckets.get_mut(key) {
        existing.hits += 1;
        existing.hits
    } else {
        let entry = buckets.entry(key.to_owned()).or_insert_with_key(|owned_key| {
            *builds += 1;
            Bucket { label: format!("bucket:{owned_key}"), hits: 0 }
        });
        entry.hits += 1;
        entry.hits
    }
}

fn main() {
    let mut buckets: HashMap<String, Bucket> = HashMap::new();
    let mut allocations = 0_u32;

    for key in ["auth", "billing", "auth", "auth", "search", "billing"] {
        let count = record_hit(&mut buckets, key, &mut allocations);
        println!("key={key:<7} hits={count} builds={allocations}");
    }
    println!("total unique buckets={} (builds={allocations})", buckets.len());
    println!("sample label: {}", buckets["auth"].label);
}