Skip to content

Commit 8f0b2c1

Browse files
committed
Merge pull request #20214 from bluss/fix-hashmap-example
hashmap: Fix the example using derived Hash + Eq Reviewed-by: alexcrichton
2 parents f6dde88 + 1114685 commit 8f0b2c1

File tree

1 file changed

+18
-10
lines changed
  • src/libstd/collections/hash

1 file changed

+18
-10
lines changed

src/libstd/collections/hash/map.rs

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -264,27 +264,35 @@ fn test_resize_policy() {
264264
/// }
265265
/// ```
266266
///
267-
/// The easiest way to use `HashMap` with a custom type is to derive `Eq` and `Hash`.
267+
/// The easiest way to use `HashMap` with a custom type as key is to derive `Eq` and `Hash`.
268268
/// We must also derive `PartialEq`.
269269
///
270270
/// ```
271271
/// use std::collections::HashMap;
272272
///
273273
/// #[deriving(Hash, Eq, PartialEq, Show)]
274-
/// struct Viking<'a> {
275-
/// name: &'a str,
276-
/// power: uint,
274+
/// struct Viking {
275+
/// name: String,
276+
/// country: String,
277277
/// }
278278
///
279+
/// impl Viking {
280+
/// /// Create a new Viking.
281+
/// pub fn new(name: &str, country: &str) -> Viking {
282+
/// Viking { name: name.to_string(), country: country.to_string() }
283+
/// }
284+
/// }
285+
///
286+
/// // Use a HashMap to store the vikings' health points.
279287
/// let mut vikings = HashMap::new();
280288
///
281-
/// vikings.insert("Norway", Viking { name: "Einar", power: 9u });
282-
/// vikings.insert("Denmark", Viking { name: "Olaf", power: 4u });
283-
/// vikings.insert("Iceland", Viking { name: "Harald", power: 8u });
289+
/// vikings.insert(Viking::new("Einar", "Norway"), 25u);
290+
/// vikings.insert(Viking::new("Olaf", "Denmark"), 24u);
291+
/// vikings.insert(Viking::new("Harald", "Iceland"), 12u);
284292
///
285-
/// // Use derived implementation to print the vikings.
286-
/// for (land, viking) in vikings.iter() {
287-
/// println!("{} at {}", viking, land);
293+
/// // Use derived implementation to print the status of the vikings.
294+
/// for (viking, health) in vikings.iter() {
295+
/// println!("{} has {} hp", viking, health);
288296
/// }
289297
/// ```
290298
#[deriving(Clone)]

0 commit comments

Comments
 (0)