]> git.lizzy.rs Git - rust.git/blobdiff - src/libstd/collections/hash/map.rs
Add examples of the Entry API to the HashMap documentation.
[rust.git] / src / libstd / collections / hash / map.rs
index 38c080febf196ac973be2adf2c3cd379cc39e97d..43bf86a00399c8da07108937e10afdf3da3a2fd9 100644 (file)
@@ -24,7 +24,6 @@
 use ops::{Deref, FnMut, FnOnce, Index};
 use option::Option::{self, Some, None};
 use rand::{self, Rng};
-use result::Result;
 
 use super::table::{
     self,
@@ -273,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`.
 ///
@@ -1347,11 +1375,15 @@ pub struct VacantEntry<'a, K: 'a, V: 'a> {
 pub enum Entry<'a, K: 'a, V: 'a> {
     /// An occupied Entry.
     #[stable(feature = "rust1", since = "1.0.0")]
-    Occupied(OccupiedEntry<'a, K, V>),
+    Occupied(
+        #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] OccupiedEntry<'a, K, V>
+    ),
 
     /// A vacant Entry.
     #[stable(feature = "rust1", since = "1.0.0")]
-    Vacant(VacantEntry<'a, K, V>),
+    Vacant(
+        #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] VacantEntry<'a, K, V>
+    ),
 }
 
 /// Possible states of a VacantEntry.