A HashMap is a generic collection of key/value pairs. All of the keys must have the same type, and all of the values must have the same type.

// MashMap needs to be imported into the current scope.
use std::collections::HashMap;

// Create an empty mutable hash map.
// The type of the keys/values must be annotated.
let mut stuff_and_things: HashMap<u8, &str> = HashMap::new();

// Add items to the hash map.
stuff_and_things.insert(1, "stuff");
stuff_and_things.insert(2, "things");

// Access the values of a hash map with square brackets and the key.
println!("{}", stuff_and_things[&1]); // => stuff
println!("{}", stuff_and_things[&2]); // => things

// Accessing a key that does not exist will result in a panic.
println!("{}", stuff_and_things[&3]); // => PANIC!


  • A hash maps data is stored on the heap.
  • A hash maps size is not known at compile time, they can grow or shrink at run time.
# rust