HashMap

Where vectors store values by an integer index, HashMaps store values by key.
HashMap keys can be booleans, integers, strings,
or any other type that implements the Eq and Hash traits.
More on this in the next section.

Like vectors, HashMaps are growable, but HashMaps can also shrink themselves
when they have excess space.
You can create a HashMap with a certain starting capacity using
HashMap::with_capacity(uint), or use HashMap::new() to get a HashMap
with a default initial capacity (recommended).

  1. use std::collections::HashMap;
  2. fn call(number: &str) -> &str {
  3. match number {
  4. "798-1364" => "We're sorry, the call cannot be completed as dialed.
  5. Please hang up and try again.",
  6. "645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
  7. What can I get for you today?",
  8. _ => "Hi! Who is this again?"
  9. }
  10. }
  11. fn main() {
  12. let mut contacts = HashMap::new();
  13. contacts.insert("Daniel", "798-1364");
  14. contacts.insert("Ashley", "645-7689");
  15. contacts.insert("Katie", "435-8291");
  16. contacts.insert("Robert", "956-1745");
  17. // Takes a reference and returns Option<&V>
  18. match contacts.get(&"Daniel") {
  19. Some(&number) => println!("Calling Daniel: {}", call(number)),
  20. _ => println!("Don't have Daniel's number."),
  21. }
  22. // `HashMap::insert()` returns `None`
  23. // if the inserted value is new, `Some(value)` otherwise
  24. contacts.insert("Daniel", "164-6743");
  25. match contacts.get(&"Ashley") {
  26. Some(&number) => println!("Calling Ashley: {}", call(number)),
  27. _ => println!("Don't have Ashley's number."),
  28. }
  29. contacts.remove(&"Ashley");
  30. // `HashMap::iter()` returns an iterator that yields
  31. // (&'a key, &'a value) pairs in arbitrary order.
  32. for (contact, &number) in contacts.iter() {
  33. println!("Calling {}: {}", contact, call(number));
  34. }
  35. }

For more information on how hashing and hash maps
(sometimes called hash tables) work, have a look at
Hash Table Wikipedia