From cec72acdcae939023d7d4e09ad1b06d49f269276 Mon Sep 17 00:00:00 2001 From: KarlWithK Date: Wed, 15 Jun 2022 02:04:18 -0500 Subject: [PATCH] Add examples using `add_modify` to btree Updated the btree's documentation to include two references to add_modify. The first is when the `Entry` API is mentioned at the beginning. With the same reasoning as HashMap's documentation, I thought it would best to keep `attack`, but show the `mana` example. 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. --- library/alloc/src/collections/btree/map.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index 6027991a0ed..7532c1d5114 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -159,6 +159,9 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT; /// // 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); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")] @@ -1135,10 +1138,12 @@ impl BTreeMap { /// /// // count the number of occurrences of letters in the vec /// for x in ["a", "b", "a", "c", "a", "b"] { - /// *count.entry(x).or_insert(0) += 1; + /// count.entry(x).and_modify(|curr| *curr += 1).or_insert(1); /// } /// /// assert_eq!(count["a"], 3); + /// assert_eq!(count["b"], 2); + /// assert_eq!(count["1"], 1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn entry(&mut self, key: K) -> Entry<'_, K, V>