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.
This commit is contained in:
Matthias Krüger 2022-06-16 09:10:21 +02:00 committed by GitHub
commit f4297b06e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 3 deletions

View File

@ -161,6 +161,9 @@
/// // 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")]
@ -1211,10 +1214,12 @@ pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
///
/// // 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["c"], 1);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A>

View File

@ -164,6 +164,9 @@
/// // 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 @@ pub fn shrink_to(&mut self, min_capacity: usize) {
/// 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);