diff options
| author | KarlWithK <cjh16@rice.edu> | 2022-06-15 01:41:56 -0500 |
|---|---|---|
| committer | KarlWithK <cjh16@rice.edu> | 2022-06-15 01:41:56 -0500 |
| commit | d3d22e1e664d33519ddc1b4bbc00cc93eed3e7be (patch) | |
| tree | 549ecf918ea7b04ab810bee22205bb5754313ffa | |
| parent | 2d1e0750792529248ed6f11061940c7203d668c9 (diff) | |
| download | rust-d3d22e1e664d33519ddc1b4bbc00cc93eed3e7be.tar.gz rust-d3d22e1e664d33519ddc1b4bbc00cc93eed3e7be.zip | |
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.
| -rw-r--r-- | library/std/src/collections/hash/map.rs | 6 |
1 files changed, 4 insertions, 2 deletions
diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index d38fecc45b2..192a21f2ffc 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -164,6 +164,9 @@ use crate::sys; /// // update a key, guarding against the key possibly not being set /// let stat = player_stats.entry("attack").or_insert(100); /// *stat += random_stat_buff(); +/// +/// // modify an entry before an insert with in-place mutation +/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100); /// ``` /// /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`]. @@ -829,8 +832,7 @@ where /// let mut letters = HashMap::new(); /// /// for ch in "a short treatise on fungi".chars() { - /// let counter = letters.entry(ch).or_insert(0); - /// *counter += 1; + /// letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1); /// } /// /// assert_eq!(letters[&'s'], 2); |
