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

Entry API का उपयोग

Entry API आपको "अगर इस label के पास अभी कोई value नहीं है, इसे एक starting one दें," कहने देता है, सब एक tidy step में।
Syntax
rust
map.entry(key).or_insert(default);
*map.entry(key).or_insert(default) += 1;
map.entry(key).or_default().push(value);

Using entry with or_insert

.entry(key).or_insert(default) default value सिर्फ तब insert करता है जब key पहले से मौजूद न हो, और दोनों तरह से value का एक mutable reference return करता है -- तुरंत उपयोग या modify करने के लिए तैयार।

उदाहरण: Using entry with or_insert

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.entry("Alice").or_insert(0);
    // Print "{:?}" to the console, substituting in `scores.get("Alice")` (with a trailing newline)
    println!("{:?}", scores.get("Alice"));
}

Counting Word Occurrences

Entry API का एक classic उपयोग occurrences count करना है: हर item के लिए, इसकी entry लें, गायब होने पर 0 default करें, फिर returned mutable reference के ज़रिए increment करें।

उदाहरण: Counting Word Occurrences

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

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `words`, set to `["a", "b", "a", "c", "b", "a"]`
    let words = ["a", "b", "a", "c", "b", "a"];
    // Declare a mutable variable `counts`, initialized to `HashMap::new()`
    let mut counts = HashMap::new();
    // Loop over `words.iter()`, binding each item to `word`
    for word in words.iter() {
        // Declare an immutable variable `count`, set to `counts.entry(*word).or_insert(0)`
        let count = counts.entry(*word).or_insert(0);
        *count += 1;
    }
    // Print "{:?}" to the console, substituting in `counts.get("a")` (with a trailing newline)
    println!("{:?}", counts.get("a"));
}

Lazy Defaults with or_insert_with

.or_insert_with(|| default()) सिर्फ तब closure चलाता है जो एक default value compute करता है जब key असल में गायब हो, expensive default values के लिए अनावश्यक काम से बचते हुए।

उदाहरण: Lazy Defaults with or_insert_with

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 `groups` (a `HashMap<&str, Vec<i32>>`), initialized to `HashMap::new()`
    let mut groups: HashMap<&str, Vec<i32>> = HashMap::new();
    groups.entry("evens").or_insert_with(Vec::new).push(2);
    groups.entry("evens").or_insert_with(Vec::new).push(4);
    // Print "{:?}" to the console, substituting in `groups.get("evens")` (with a trailing newline)
    println!("{:?}", groups.get("evens"));
}

Modifying Existing Values in Place

चूंकि .entry().or_insert() एक mutable reference return करता है, आप value को सीधे update करने के लिए इसे * से dereference कर सकते हैं, जो per-key totals accumulate करने के लिए standard pattern है।

उदाहरण: Modifying Existing Values in Place

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 `totals` (a `HashMap<&str, i32>`), initialized to `HashMap::new()`
    let mut totals: HashMap<&str, i32> = HashMap::new();
    // Loop over `vec![("tea", 3), ("coffee", 5), ("tea", 2)]`, binding each item to `(name, amount)`
    for (name, amount) in vec![("tea", 3), ("coffee", 5), ("tea", 2)] {
        *totals.entry(name).or_insert(0) += amount;
    }
    // Print "{:?}" to the console, substituting in `totals.get("tea")` (with a trailing newline)
    println!("{:?}", totals.get("tea"));
}
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. .contains_key() से manually जांचना और फिर अलग से .insert() call करना, बजाय ज़्यादा idiomatic single .entry() call के।
  2. यह भूल जाना कि .or_insert() एक mutable reference return करता है, जिसे आप फिर सीधे modify कर सकते हैं, जैसे एक counter increment करना।
  3. .or_insert(expensive_computation()) उपयोग करना जब default value compute करना महंगा हो -- .or_insert_with() सिर्फ ज़रूरत पड़ने पर closure चलाता है।
चैप्टर सारांश
  • .entry(key) एक handle return करता है जो उस key के slot को represent करता है, चाहे यह अभी मौजूद हो या नहीं।
  • .or_insert(default) सिर्फ तब एक default value insert करता है जब key गायब हो, और हमेशा value का एक mutable reference return करता है।
  • .or_insert_with(|| ...) default को सिर्फ असल में ज़रूरत पड़ने पर lazily compute करता है।
  • Entry API एक HashMap के साथ counting या accumulating patterns implement करने का idiomatic तरीका है।
🔒

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.