← 中文资源

简体中文版本

BTreeMap entry 插入或更新

对 BTreeMap::entry 做 match:一次查找就完成插入或就地累加;BTreeMap 遍历天然按键有序,报表输出无需再排序。

阅读英文原文

实现说明

BTreeMap entry 插入或更新以函数 main为骨架。 驱动整个流程的是 for item in ["widget", "gadget", "widget"] 这一个循环。match 表达式是穷尽的——编译器强制没有遗漏的分支。

常见问题

「BTreeMap entry 插入或更新」这个示例怎么运行?

直接执行即可——程序只依赖运行时自身。

核心语句

Entry::Occupied(mut slot) => {
    *slot.get_mut() += 2;
}
Entry::Vacant(slot) => {
    slot.insert(1);
}

代码示例

use std::collections::btree_map::Entry;
use std::collections::BTreeMap;

fn main() {
    let mut stock = BTreeMap::from([("widget", 4u32)]);

    // entry is one lookup: match it to insert or update in place
    for item in ["widget", "gadget", "widget"] {
        match stock.entry(item) {
            Entry::Occupied(mut slot) => {
                *slot.get_mut() += 2;
            }
            Entry::Vacant(slot) => {
                slot.insert(1);
            }
        }
    }

    // BTreeMap iteration is sorted by key, no re-sort needed
    for (name, count) in &stock {
        println!("{name}: {count}");
    }
}