HashMap and Set in Rust

 

What is a HashMap?

A HashMap in Rust is like a magic dictionary 🪄 that stores key-value pairs. It lets you quickly look up a value using a key, making it super useful for storing and retrieving data efficiently!

Creating a HashMap

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 100);
    scores.insert("Bob", 90);
    println!("Scores: {:?}", scores);
}
  • Fast lookups using keys.
  • Keys and values can be of any type (as long as they implement Eq and Hash).
  • Efficient storage for unique mappings.

Accessing Values in a HashMap

To get a value, use .get(). It returns an Option, so we must handle cases where the key doesn’t exist.

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 100);
    
    match scores.get("Alice") {
        Some(score) => println!("Alice's score: {}", score),
        None => println!("No score found for Alice"),
    }
}

 .get() prevents crashes by returning None if the key is missing!

What is a HashSet?

A HashSet is a collection of unique values. It’s like a club where no duplicate members are allowed!

Creating a HashSet

use std::collections::HashSet;

fn main() {
    let mut numbers = HashSet::new();
    numbers.insert(10);
    numbers.insert(20);
    numbers.insert(10); // Duplicate! Won't be added.
    println!("Numbers: {:?}", numbers);
}

No duplicates allowed!
Fast lookup times (like HashMap, but only keys).
Great for checking existence of items.

When to Use HashMap vs HashSet?

  • Use HashMap when you need key-value storage.
  • Use HashSet when you only care about unique values.

So whether you’re mapping treasures  or creating a VIP list, Rust’s HashMap and HashSet have got your back!

Post a Comment

0 Comments