HashMap

Standard hash map with protection against HashDoS attacks:

  1. use std::collections::HashMap;
  2. fn main() {
  3.     let mut page_counts = HashMap::new();
  4.     page_counts.insert("Adventures of Huckleberry Finn", 207);
  5.     page_counts.insert("Grimms' Fairy Tales", 751);
  6.     page_counts.insert("Pride and Prejudice", 303);
  7.     if !page_counts.contains_key("Les Misérables") {
  8.         println!(
  9.             "We know about {} books, but not Les Misérables.",
  10.             page_counts.len()
  11.         );
  12.     }
  13.     for book in ["Pride and Prejudice", "Alice's Adventure in Wonderland"] {
  14.         match page_counts.get(book) {
  15.             Some(count) => println!("{book}: {count} pages"),
  16.             None => println!("{book} is unknown."),
  17.         }
  18.     }
  19.     // Use the .entry() method to insert a value if nothing is found.
  20.     for book in ["Pride and Prejudice", "Alice's Adventure in Wonderland"] {
  21.         let page_count: &mut i32 = page_counts.entry(book).or_insert(0);
  22.         *page_count += 1;
  23.     }
  24.     println!("{page_counts:#?}");
  25. }

This slide should take about 5 minutes.

  • HashMap is not defined in the prelude and needs to be brought into scope.

  • Try the following lines of code. The first line will see if a book is in the hashmap and if not return an alternative value. The second line will insert the alternative value in the hashmap if the book is not found.

    1. let pc1 = page_counts
    2. .get("Harry Potter and the Sorcerer's Stone")
    3. .unwrap_or(&336);
    4. let pc2 = page_counts
    5. .entry("The Hunger Games")
    6. .or_insert(374);
  • Unlike vec!, there is unfortunately no standard hashmap! macro.

    • Although, since Rust 1.56, HashMap implements From<[(K, V); N]>;+N%5D%3E-for-HashMap%3CK,+V,+RandomState%3E), which allows us to easily initialize a hash map from a literal array:

      1. let page_counts = HashMap::from([
      2. ("Harry Potter and the Sorcerer's Stone".to_string(), 336),
      3. ("The Hunger Games".to_string(), 374),
      4. ]);
  • Alternatively HashMap can be built from any Iterator which yields key-value tuples.

  • This type has several “method-specific” return types, such as std::collections::hash_map::Keys. These types often appear in searches of the Rust docs. Show students the docs for this type, and the helpful link back to the keys method.