HashMap in Rust

A HashMap in Rust is a powerful and flexible data structure used to store key-value pairs. It is part of Rust's standard library and provides constant-time complexity for insertion and retrieval operations, making it an efficient choice for many applications. However, it is not included in the Rust prelude, so it must be explicitly imported into your code. This entry synthesizes information from various Rust books to provide a comprehensive understanding of HashMap.

Overview

A HashMap is a collection that stores key-value pairs, where each key maps to a specific value. The keys in a HashMap are unordered, meaning that when you iterate over the keys, they may not appear in the order you inserted them. This unordered nature is due to the underlying hash function used to store the keys. Rust's HashMap is optimized for speed and safety, using the Siphash-1-3 function by default, which balances performance and security. For cases where ordered keys are necessary, a BTreeMap can be used instead.

Creating a HashMap

You can create a HashMap by collecting key-value pairs from two vectors. Here's an example:

use std::collections::HashMap;

fn main() {
    let some_keys = vec![0, 1, 2, 3, 4, 5];
    let some_values = vec!["zero", "one", "two", "three", "four", "five"];

    let number_word_hashmap = some_keys
        .into_iter()
        .zip(some_values.into_iter())
        .collect::<HashMap<_, _>>();

    println!(
        "The value at key 2 is: {}",
        number_word_hashmap.get(&2).unwrap()
    );
}

This code will print The value at key 2 is: two.

Inserting and Retrieving Values

To add items to a HashMap, use the .insert() method. If a key already exists, .insert() will overwrite its value. To retrieve values, use the .get() method, which safely returns an Option. If the key exists, .get() returns Some(value), and if not, it returns None, preventing the program from panicking.

Example: Overwriting Values

use std::collections::HashMap;

fn main() {
    let mut book_hashmap = HashMap::new();

    book_hashmap.insert(1, "L'Allemagne Moderne");
    book_hashmap.insert(1, "Le Petit Prince");
    book_hashmap.insert(1, "섀도우 오브 유어 스마일");
    book_hashmap.insert(1, "Eye of the World");

    println!("{:?}", book_hashmap.get(&1));
}

This prints Some("Eye of the World") because it was the last value inserted for the key 1.

Iterating Over a HashMap

When iterating over a HashMap, the order of keys is not guaranteed. Here's an example demonstrating this behavior:

use std::collections::HashMap;

struct City {
    name: String,
    population: HashMap<i32, i32>,
}

fn main() {
    let mut tallinn = City {
        name: "Tallinn".to_string(),
        population: HashMap::new(),
    };

    tallinn.population.insert(2020, 437_619);
    tallinn.population.insert(1372, 3_250);
    tallinn.population.insert(1851, 24_000);

    for (year, population) in tallinn.population {
        println!("In {year}, Tallinn had a population of {population}.");
    }
}

In this example, the keys 2020, 1372, and 1851 may be printed in any order.

Using Custom Hashers

Rust allows for the use of custom hashers with HashMap. For example, you can use MetroHash for scenarios where performance is a critical concern.

use metrohash::MetroBuildHasher;
use std::collections::HashMap;

let mut map = HashMap::<String, String, MetroBuildHasher>::default();
map.insert("hello?".into(), "Hello!".into());

println!("{:?}", map.get("hello?"));

This demonstrates the flexibility of Rust's HashMap with custom hashers.

HashMap in Rust Macros

When using HashMap within macros, it is important to import it explicitly using std::collections::HashMap to avoid compilation errors. Additionally, using the full path helps prevent conflicts with user-defined structs that may have the same name.

Example: Generating Code with HashMap

fn generate_inserts(yaml_values: HashMap<String, String>) -> Vec<TokenStream> {
    yaml_values.iter().map(|v| {
        let key = v.0;
        let value = v.1;
        quote!(map.insert(#key.to_string(), #value.to_string());)
    }).collect()
}

pub fn generate_config_struct(yaml_values: HashMap<String, String>) -> TokenStream {
    let inserts = generate_inserts(yaml_values);
    quote! {
        pub struct Config(
            pub std::collections::HashMap<String,String>
        );

        impl Config {
            pub fn new() -> Self {
                let mut map = std::collections::HashMap::new();
                #(#inserts)*
                Config(map)
            }
        }
    }
}

By following these practices, you can effectively use HashMap in Rust macros while avoiding common pitfalls related to imports and naming conflicts.

| Book Title | Usage of hashmap | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Learn Rust in a Month of Lunches](https://www.manning.com/books/learn-rust-in-a-month-of-lunches) | Discusses `HashMap` as a versatile data structure for key-value pairs, with examples of creation, insertion, and iteration. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-8/134) | Covers basic operations like insertion and retrieval, and mentions `BTreeMap` for ordered keys. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-6/9) | Connects `HashMap` with `BTreeMap` for ordered key storage. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-6/209) | Provides code examples for creating and using `HashMap`, including overwriting values and checking for existing keys. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-8/134) | Demonstrates practical use cases like storing city populations and book titles. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-8/134) |
| [Code Like a Pro in Rust](https://www.manning.com/books/code-like-a-pro-in-rust) | Highlights `HashMap` as a collection type for constant-time retrieval, optimized for speed and safety. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-4/274) | Discusses implementation details, including the use of `Eq`, `Hash`, and `BuildHasher` traits. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-4/98) | Explores custom hashers like `MetroHash` for performance optimization. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-4/105) | Includes code snippets for using `HashMap` with custom hashers. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-4/listing--4-9) | Focuses on performance-critical applications using custom hashers. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-4/105) |
| [Write Powerful Rust Macros](https://www.manning.com/books/write-powerful-rust-macros) | Discusses `HashMap` usage within macros, emphasizing import requirements and potential pitfalls. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-10/29) | Addresses issues like import conflicts and user-defined `HashMap` structs. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-10/29) | Highlights the importance of using full paths to avoid naming conflicts. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-10/29) | Provides examples of generating code with `HashMap` in macros. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-10/29) | Demonstrates macro usage for generating configuration structures with `HashMap`. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-10/29) |

FAQ (Frequently asked questions)

How does Rust's HashMap compare to hash maps in other languages?

What hashing function does Rust's HashMap use by default?

How do you add items to a HashMap in Rust?

What happens if you insert a key that already exists in a HashMap?

What is the alternative to HashMap if you need keys in order?

What does the example code print when accessing key 2 in the HashMap?