Skip to content

Commit d3d22e1

Browse files
committed
Add examples using add_modify to HashMap
Updated the HashMap's documentation to include two references to add_modify. The first is when the `Entry` API is mentioned at the beginning. I was hesitant to change the "attack" example (although I believe that it is perfect example of where `add_modify` should be used) because both uses work equally, but one is more idiomatic (`add_modify`). The second is with the `entry` function that is used for the `Entry` API. The code example was a perfect use for `add_modify`, which is why it was changed to reflect that.
1 parent 2d1e075 commit d3d22e1

File tree

1 file changed

+4
-2
lines changed
  • library/std/src/collections/hash

1 file changed

+4
-2
lines changed

library/std/src/collections/hash/map.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,9 @@ use crate::sys;
164164
/// // update a key, guarding against the key possibly not being set
165165
/// let stat = player_stats.entry("attack").or_insert(100);
166166
/// *stat += random_stat_buff();
167+
///
168+
/// // modify an entry before an insert with in-place mutation
169+
/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
167170
/// ```
168171
///
169172
/// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
@@ -829,8 +832,7 @@ where
829832
/// let mut letters = HashMap::new();
830833
///
831834
/// for ch in "a short treatise on fungi".chars() {
832-
/// let counter = letters.entry(ch).or_insert(0);
833-
/// *counter += 1;
835+
/// letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
834836
/// }
835837
///
836838
/// assert_eq!(letters[&'s'], 2);

0 commit comments

Comments
 (0)