From 11146856969515807f85796028d8a214aaac0528 Mon Sep 17 00:00:00 2001 From: bluss Date: Thu, 25 Dec 2014 02:17:48 +0100 Subject: [PATCH] hashmap: Fix the example using derived Hash + Eq The example derived Hash + Eq on a type that was used as *values* for a hashmap.. for the example to make sense, we have to use a custom *key* type. Write a slightly more involved example, still using Vikings, but this time as key. I preferred using String over &str here, since that's the typical usage and we might want to lead users down that path. --- src/libstd/collections/hash/map.rs | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index d749cd77cef..8c6e72ea2ae 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -264,27 +264,35 @@ fn test_resize_policy() { /// } /// ``` /// -/// The easiest way to use `HashMap` with a custom type is to derive `Eq` and `Hash`. +/// The easiest way to use `HashMap` with a custom type as key is to derive `Eq` and `Hash`. /// We must also derive `PartialEq`. /// /// ``` /// use std::collections::HashMap; /// /// #[deriving(Hash, Eq, PartialEq, Show)] -/// struct Viking<'a> { -/// name: &'a str, -/// power: uint, +/// struct Viking { +/// name: String, +/// country: String, /// } /// +/// impl Viking { +/// /// Create a new Viking. +/// pub fn new(name: &str, country: &str) -> Viking { +/// Viking { name: name.to_string(), country: country.to_string() } +/// } +/// } +/// +/// // Use a HashMap to store the vikings' health points. /// let mut vikings = HashMap::new(); /// -/// vikings.insert("Norway", Viking { name: "Einar", power: 9u }); -/// vikings.insert("Denmark", Viking { name: "Olaf", power: 4u }); -/// vikings.insert("Iceland", Viking { name: "Harald", power: 8u }); +/// vikings.insert(Viking::new("Einar", "Norway"), 25u); +/// vikings.insert(Viking::new("Olaf", "Denmark"), 24u); +/// vikings.insert(Viking::new("Harald", "Iceland"), 12u); /// -/// // Use derived implementation to print the vikings. -/// for (land, viking) in vikings.iter() { -/// println!("{} at {}", viking, land); +/// // Use derived implementation to print the status of the vikings. +/// for (viking, health) in vikings.iter() { +/// println!("{} has {} hp", viking, health); /// } /// ``` #[deriving(Clone)]