3 Where vectors store values by an integer index, `HashMap`s store values by key.
4 `HashMap` keys can be booleans, integers, strings,
5 or any other type that implements the `Eq` and `Hash` traits.
6 More on this in the next section.
8 Like vectors, `HashMap`s are growable, but HashMaps can also shrink themselves
9 when they have excess space.
10 You can create a HashMap with a certain starting capacity using
11 `HashMap::with_capacity(uint)`, or use `HashMap::new()` to get a HashMap
12 with a default initial capacity (recommended).
15 use std::collections::HashMap;
17 fn call(number: &str) -> &str {
19 "798-1364" => "We're sorry, the call cannot be completed as dialed.
20 Please hang up and try again.",
21 "645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
22 What can I get for you today?",
23 _ => "Hi! Who is this again?"
28 let mut contacts = HashMap::new();
30 contacts.insert("Daniel", "798-1364");
31 contacts.insert("Ashley", "645-7689");
32 contacts.insert("Katie", "435-8291");
33 contacts.insert("Robert", "956-1745");
35 // Takes a reference and returns Option<&V>
36 match contacts.get(&"Daniel") {
37 Some(&number) => println!("Calling Daniel: {}", call(number)),
38 _ => println!("Don't have Daniel's number."),
41 // `HashMap::insert()` returns `None`
42 // if the inserted value is new, `Some(value)` otherwise
43 contacts.insert("Daniel", "164-6743");
45 match contacts.get(&"Ashley") {
46 Some(&number) => println!("Calling Ashley: {}", call(number)),
47 _ => println!("Don't have Ashley's number."),
50 contacts.remove(&"Ashley");
52 // `HashMap::iter()` returns an iterator that yields
53 // (&'a key, &'a value) pairs in arbitrary order.
54 for (contact, &number) in contacts.iter() {
55 println!("Calling {}: {}", contact, call(number));
60 For more information on how hashing and hash maps
61 (sometimes called hash tables) work, have a look at
62 [Hash Table Wikipedia][wiki-hash]
64 [wiki-hash]: https://en.wikipedia.org/wiki/Hash_table