diff options
| author | bluss <bluss> | 2014-12-25 02:17:48 +0100 |
|---|---|---|
| committer | bluss <bluss> | 2014-12-25 02:17:48 +0100 |
| commit | 11146856969515807f85796028d8a214aaac0528 (patch) | |
| tree | 6cd2e5e5f6ead9467e7a20d520fab460e8360558 /src/libstd | |
| parent | 7e11b22713aebd28ceaaa2ecef937c9b9d247c2f (diff) | |
| download | rust-11146856969515807f85796028d8a214aaac0528.tar.gz rust-11146856969515807f85796028d8a214aaac0528.zip | |
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.
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/collections/hash/map.rs | 28 |
1 files 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)] |
