知识卡片

普通读书笔记卡 · 10646.b · 生成模型:未记录

按键入口统一三种更新

理解等级:中级

重复 insert 同一键会用新值覆盖旧值。若只想为缺失键设初值,可用 entry(key).or_insert(default)。它返回实际值的 &mut V,可以选择保留这个值,也可以解引用后就地更新。词频统计用缺失值 0 启动计数,然后对每次出现执行加一。

相关卡片 [[哈希表按键借用查询]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 常用集合 Updating a Hash Map · 查看原书依据

      The or_insert method on Entry is defined to return a mutable reference to the value for the corresponding Entry key if that key exists, and if not, it inserts the parameter as the new value for this key and returns a mutable reference to the new value. This technique is much cleaner than writing the logic ourselves and, in addition, plays more nicely with the borrow checker.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第08章 常用集合(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c08.xhtml`,块 0205) - 结论依据:原文说明 Entry 无论已存在还是首次添加,都会返回当前值的可变引用。 - 原始内容:The or_insert method on Entry is defined to return a mutable reference to the value for the corresponding Entry key if that key exists, and if not, it inserts the parameter as the new value for this key and returns a mutable reference to the new value. This technique is much cleaner than writing the logic ourselves and, in addition, plays more nicely with the borrow checker.