summary refs log tree commit diff
path: root/library/std/src
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2022-06-16 09:10:21 +0200
committerGitHub <noreply@github.com>2022-06-16 09:10:21 +0200
commitf4297b06e8db75fcf6b3feeae91739ba6ffd4d66 (patch)
tree4a7f077897e818067ac1f988ccd205925b68e80a /library/std/src
parent95be954af412e4473499a3745c84583c545f15e5 (diff)
parent791923aacbbab0933f8ff1108a120194addccf6b (diff)
downloadrust-f4297b06e8db75fcf6b3feeae91739ba6ffd4d66.tar.gz
rust-f4297b06e8db75fcf6b3feeae91739ba6ffd4d66.zip
Rollup merge of #98125 - KarlWithK:entry_add_modify_doc, r=Dylan-DPC
Entry and_modify doc

This PR modifies the documentation for [HashMap](https://doc.rust-lang.org/std/collections/struct.HashMap.html#) and [BTreeMap](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#) by introducing examples for `and_modify`. `and_modify` is a function that tends to give more idiomatic rust code when dealing with these data structures -- yet it lacked examples and was hidden away. This PR adds that and addresses #98122.

I've made some choices which I tried to explain in my commits. This is my first time contributing to rust, so hopefully, I made the right choices.
Diffstat (limited to 'library/std/src')
-rw-r--r--library/std/src/collections/hash/map.rs6
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);