summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorNathan Kleyn <nathan@nathankleyn.com>2016-01-19 21:54:11 +0000
committerNathan Kleyn <nathan@nathankleyn.com>2016-01-19 21:54:11 +0000
commitccba72e660a6b1e183e7d96d1e51d5e4952ba053 (patch)
treea6e87703f433cab13659d82163f38c82007f0646 /src/libstd
parent84157dbd4c7420e3e5b4dd22e4ff244889aa6275 (diff)
downloadrust-ccba72e660a6b1e183e7d96d1e51d5e4952ba053.tar.gz
rust-ccba72e660a6b1e183e7d96d1e51d5e4952ba053.zip
Add examples of the Entry API to the HashMap documentation.
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 #29348.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/collections/hash/map.rs29
1 files changed, 29 insertions, 0 deletions
diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs
index e43101b7c9d..43bf86a0039 100644
--- a/src/libstd/collections/hash/map.rs
+++ b/src/libstd/collections/hash/map.rs
@@ -272,6 +272,35 @@ fn test_resize_policy() {
 /// }
 /// ```
 ///
+/// `HashMap` also implements an [`Entry API`](#method.entry), which allows
+/// for more complex methods of getting, setting, updating and removing keys and
+/// their values:
+///
+/// ```
+/// use std::collections::HashMap;
+///
+/// // type inference lets us omit an explicit type signature (which
+/// // would be `HashMap<&str, u8>` in this example).
+/// let mut player_stats = HashMap::new();
+///
+/// fn random_stat_buff() -> u8 {
+///   // could actually return some random value here - let's just return
+///   // some fixed value for now
+///   42
+/// }
+///
+/// // insert a key only if it doesn't already exist
+/// player_stats.entry("health").or_insert(100);
+///
+/// // insert a key using a function that provides a new value only if it
+/// // doesn't already exist
+/// player_stats.entry("defence").or_insert_with(random_stat_buff);
+///
+/// // update a key, guarding against the key possibly not being set
+/// let stat = player_stats.entry("attack").or_insert(100);
+/// *stat += random_stat_buff();
+/// ```
+///
 /// The easiest way to use `HashMap` with a custom type as key is to derive `Eq` and `Hash`.
 /// We must also derive `PartialEq`.
 ///