Skip to content

Commit cec72ac

Browse files
committed
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.
1 parent d3d22e1 commit cec72ac

File tree

1 file changed

+6
-1
lines changed
  • library/alloc/src/collections/btree

1 file changed

+6
-1
lines changed

library/alloc/src/collections/btree/map.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,9 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
159159
/// // update a key, guarding against the key possibly not being set
160160
/// let stat = player_stats.entry("attack").or_insert(100);
161161
/// *stat += random_stat_buff();
162+
///
163+
/// // modify an entry before an insert with in-place mutation
164+
/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
162165
/// ```
163166
#[stable(feature = "rust1", since = "1.0.0")]
164167
#[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
@@ -1135,10 +1138,12 @@ impl<K, V> BTreeMap<K, V> {
11351138
///
11361139
/// // count the number of occurrences of letters in the vec
11371140
/// for x in ["a", "b", "a", "c", "a", "b"] {
1138-
/// *count.entry(x).or_insert(0) += 1;
1141+
/// count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
11391142
/// }
11401143
///
11411144
/// assert_eq!(count["a"], 3);
1145+
/// assert_eq!(count["b"], 2);
1146+
/// assert_eq!(count["1"], 1);
11421147
/// ```
11431148
#[stable(feature = "rust1", since = "1.0.0")]
11441149
pub fn entry(&mut self, key: K) -> Entry<'_, K, V>

0 commit comments

Comments
 (0)