← Back to Rust Course | Chapter 9: Collections | Lesson 3 of 6

HashMap के Basics

एक HashMap आपको अपने चुने labels के तहत values store करने देता है, एक labeled filing cabinet की तरह जिसे आप नाम से instantly search कर सकते हैं।
Syntax
rust
let mut name: HashMap<K, V> = HashMap::new();
name.insert(key, value);
name.get(&key)
name.remove(&key);

Creating and Inserting

एक HashMap HashMap::new() से बनाया जाता है और .insert(key, value) से populate किया जाता है, जो उस key के लिए value store या overwrite करता है।

उदाहरण: Creating and Inserting

markup
// Bring `std::collections::HashMap` into scope
use std::collections::HashMap;

// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `scores`, initialized to `HashMap::new()`
    let mut scores = HashMap::new();
    scores.insert("Alice", 90);
    scores.insert("Bob", 85);
    // Print "{:?}" to the console, substituting in `scores.get("Alice")` (with a trailing newline)
    println!("{:?}", scores.get("Alice"));
}

Retrieving Values Safely

.get(&key) एक Option<&V> return करता है, आपको सुरक्षित रूप से उस case को handle करने देते हुए जहां एक key map में मौजूद नहीं है।

उदाहरण: Retrieving Values Safely

markup
// Bring `std::collections::HashMap` into scope
use std::collections::HashMap;

// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `ages`, initialized to `HashMap::new()`
    let mut ages = HashMap::new();
    ages.insert("Sam", 25);
    // Match on `ages.get("Sam")` and branch by pattern
    match ages.get("Sam") {
        Some(age) => println!("Sam is {}", age),
        None => println!("Sam not found"),
    }
}

Overwriting an Existing Key

किसी पहले से मौजूद key के लिए एक value insert करना चुपचाप पुरानी value replace कर देता है -- default रूप से कोई error या warning नहीं।

उदाहरण: Overwriting an Existing Key

markup
// Bring `std::collections::HashMap` into scope
use std::collections::HashMap;

// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `inventory`, initialized to `HashMap::new()`
    let mut inventory = HashMap::new();
    inventory.insert("apples", 10);
    inventory.insert("apples", 15);
    // Print "{:?}" to the console, substituting in `inventory.get("apples")` (with a trailing newline)
    println!("{:?}", inventory.get("apples"));
}

Iterating a HashMap

&map पर एक for loop (&key, &value) pairs yield करता है, हालांकि iteration का order insertion order से मेल खाने की गारंटी नहीं है।

उदाहरण: Iterating a HashMap

markup
// Bring `std::collections::HashMap` into scope
use std::collections::HashMap;

// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `colors`, initialized to `HashMap::new()`
    let mut colors = HashMap::new();
    colors.insert("red", "#FF0000");
    colors.insert("blue", "#0000FF");
    // Declare a mutable variable `keys` (a `Vec<&&str>`), initialized to `colors.keys().collect()`
    let mut keys: Vec<&&str> = colors.keys().collect();
    keys.sort();
    // Loop over `keys`, binding each item to `k`
    for k in keys {
        // Print "{}: {}" to the console, substituting in `k, colors[k]` (with a trailing newline)
        println!("{}: {}", k, colors[k]);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. इसे उपयोग करने की कोशिश करने से पहले use std::collections::HashMap; भूल जाना।
  2. यह मान लेना कि HashMap कुछ दूसरी languages की dictionaries की तरह insertion order संरक्षित रखता है -- Rust के HashMap की कोई guaranteed order नहीं।
  3. पहले से मौजूद key के साथ .insert() call करना और यह देखकर हैरान होना कि पुरानी value चुपचाप overwrite हो गई।
चैप्टर सारांश
  • HashMap<K, V> key-value pairs store करता है और use std::collections::HashMap; चाहता है।
  • .insert(key, value) एक entry जोड़ता या overwrite करता है; .get(&key) इसे एक Option के रूप में retrieve करता है।
  • किसी HashMap पर iteration order की गारंटी नहीं और runs के बीच बदल सकता है।
  • Keys को Eq और Hash traits implement करना चाहिए, जो ज़्यादातर built-in types पहले से करते हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.