0Pricing
Learn Rust Coding · درس

HashMaps

تخزين المفتاح والقيمة

HashMaps درس مجاني في Learn Rust Coding على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Learn Rust Coding، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Learn Rust Coding 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

What Is a HashMap?

A HashMap<K, V> stores key-value pairs. You look up values by their key instead of by position.

You must import it from the standard library.

use std::collections::HashMap;

fn main() {
    let map: HashMap<String, i32> = HashMap::new();
    println!("{} entries", map.len());
}

Importing HashMap

HashMap is not in the prelude, so add this line at the top of your file:

  • use std::collections::HashMap;
use std::collections::HashMap;

fn main() {
    let scores: HashMap<&str, i32> = HashMap::new();
    println!("empty: {}", scores.is_empty());
}

Inserting Pairs

Add entries with insert, giving a key and a value. The map must be mut.

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 90);
    scores.insert("Bob", 85);
    println!("{:?}", scores);
}

Looking Up Values

Use get to read a value by key. It returns an Option — Some(value) if found, None otherwise.

use std::collections::HashMap;

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

Updating a Value

Calling insert with an existing key replaces the old value.

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("count", 1);
    map.insert("count", 5); // overwrites
    println!("{:?}", map.get("count"));
}

Insert Only If Absent

The entry API with or_insert inserts a default only if the key is missing.

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.entry("x").or_insert(10);
    map.entry("x").or_insert(99); // ignored, key exists
    println!("{:?}", map.get("x"));
}

Counting with entry

A classic pattern: count occurrences by getting a mutable reference with or_insert and incrementing it.

use std::collections::HashMap;

fn main() {
    let text = "a b a c b a";
    let mut counts = HashMap::new();
    for word in text.split_whitespace() {
        let c = counts.entry(word).or_insert(0);
        *c += 1;
    }
    println!("{:?}", counts);
}

Iterating Entries

Loop over a HashMap to visit every key-value pair. The order is not guaranteed.

use std::collections::HashMap;

fn main() {
    let mut ages = HashMap::new();
    ages.insert("Tom", 30);
    ages.insert("Sue", 25);
    for (name, age) in &ages {
        println!("{} is {}", name, age);
    }
}

Removing Entries

Delete a pair with remove. It returns the removed value as an Option.

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("key", 42);
    let removed = map.remove("key");
    println!("removed {:?}, len {}", removed, map.len());
}

Checking for a Key

Use contains_key to test whether a key exists without retrieving its value.

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("on", true);
    println!("{}", map.contains_key("on"));
    println!("{}", map.contains_key("off"));
}

Default with unwrap_or

When reading, you can supply a fallback with unwrap_or instead of matching the Option.

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("a", 1);
    let value = map.get("missing").unwrap_or(&0);
    println!("{}", value);
}

Quick Check

Recall how HashMap lookups behave.

Recap

HashMaps in Rust:

  • HashMap<K, V> stores key-value pairs; import from std::collections.
  • insert adds or overwrites; get returns an Option.
  • entry().or_insert() inserts only if absent.
  • Iterate with for (k, v) in &map.
use std::collections::HashMap;

fn main() {
    let mut inventory = HashMap::new();
    inventory.insert("apples", 3);
    *inventory.entry("apples").or_insert(0) += 2;
    println!("{:?}", inventory.get("apples"));
}

الأسئلة الشائعة

هل درس «HashMaps» مجاني؟

نعم — نص درس «HashMaps» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Learn Rust Coding، انتقل إلى CoddyKit PRO. تتضمن دورة Learn Rust Coding 4 دروس في المجموع.

ماذا ستتعلم في «HashMaps»؟

تخزين المفتاح والقيمة تتمرن على Learn Rust Coding مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Learn Rust Coding؟

لا تُشترط خبرة سابقة. Learn Rust Coding على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «HashMaps»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Learn Rust Coding هذا؟

نعم. كل درس في Learn Rust Coding يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. Vectors
  2. Strings و&str
  3. HashMaps
  4. التكرار على المجموعات
← العودة إلى Learn Rust Coding