Skip to content

Commit 97f9e26

Browse files
committed
Rollup merge of rust-lang#31035 - nathankleyn:improve-visibility-of-entry-api, r=steveklabnik
Responding to [a thread of discussion on the Rust subreddit](https://www.reddit.com/r/rust/comments/3racik/mutable_lifetimes_are_too_long_when_matching_an/), it was identified that the presence of the Entry API is not duly publicised. This commit aims to add some reasonable examples of common usages of this API to the main example secion of the `HashMap` documentation. This is part of issue rust-lang#29348.
2 parents 068fa97 + ccba72e commit 97f9e26

File tree

1 file changed

+29
-0
lines changed
  • src/libstd/collections/hash

1 file changed

+29
-0
lines changed

src/libstd/collections/hash/map.rs

+29
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,35 @@ fn test_resize_policy() {
272272
/// }
273273
/// ```
274274
///
275+
/// `HashMap` also implements an [`Entry API`](#method.entry), which allows
276+
/// for more complex methods of getting, setting, updating and removing keys and
277+
/// their values:
278+
///
279+
/// ```
280+
/// use std::collections::HashMap;
281+
///
282+
/// // type inference lets us omit an explicit type signature (which
283+
/// // would be `HashMap<&str, u8>` in this example).
284+
/// let mut player_stats = HashMap::new();
285+
///
286+
/// fn random_stat_buff() -> u8 {
287+
/// // could actually return some random value here - let's just return
288+
/// // some fixed value for now
289+
/// 42
290+
/// }
291+
///
292+
/// // insert a key only if it doesn't already exist
293+
/// player_stats.entry("health").or_insert(100);
294+
///
295+
/// // insert a key using a function that provides a new value only if it
296+
/// // doesn't already exist
297+
/// player_stats.entry("defence").or_insert_with(random_stat_buff);
298+
///
299+
/// // update a key, guarding against the key possibly not being set
300+
/// let stat = player_stats.entry("attack").or_insert(100);
301+
/// *stat += random_stat_buff();
302+
/// ```
303+
///
275304
/// The easiest way to use `HashMap` with a custom type as key is to derive `Eq` and `Hash`.
276305
/// We must also derive `PartialEq`.
277306
///

0 commit comments

Comments
 (0)