File tree 1 file changed +29
-0
lines changed
src/libstd/collections/hash
1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change @@ -272,6 +272,35 @@ fn test_resize_policy() {
272
272
/// }
273
273
/// ```
274
274
///
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
+ ///
275
304
/// The easiest way to use `HashMap` with a custom type as key is to derive `Eq` and `Hash`.
276
305
/// We must also derive `PartialEq`.
277
306
///
You can’t perform that action at this time.
0 commit comments