ข้ามไปยังเนื้อหา

HashMap

HashMap<K, V> Map Key ของประเภท K ไปยัง Value ของประเภท V โดยใช้ Hash Function ภายในเพื่อให้ได้ O(1) เฉลี่ยสำหรับการ Insert และค้นหา

use std::collections::HashMap;
let mut scores: HashMap<String, u32> = HashMap::new();

Key ต้อง Implement Eq และ Hash ประเภท Key ทั่วไป — String, &str, จำนวนเต็ม — ทำเช่นนั้นอยู่แล้ว

scores.insert(String::from("Alice"), 100);
scores.insert(String::from("Bob"), 85);
// get คืน Option<&V>
if let Some(score) = scores.get("Alice") {
println!("Alice: {}", score);
}
// Index Syntax — Panic ถ้า Key ไม่มี
let bob_score = scores["Bob"];

ควรใช้ .get(key) ใน Production Code เพื่อจัดการกรณี Key ไม่มีอย่างถูกต้อง

entry API ให้วิธีที่สะอาดในการ Insert ค่าเฉพาะเมื่อ Key ยังไม่มี หลีกเลี่ยงการ Lookup สองครั้ง:

// Insert 70 สำหรับ "Dave" ถ้า "Dave" ยังไม่มีใน Map
scores.entry(String::from("Dave")).or_insert(70);
// เพิ่ม Counter — Insert 0 ถ้ายังไม่มี แล้วบวก 1
let count = scores.entry(String::from("Eve")).or_insert(0);
*count += 1;

or_insert คืน &mut V ที่ชี้ไปยัง Value เพื่อให้อัปเดตได้ทันที

HashMap ไม่รับประกัน Order การ Iterate การรันโปรแกรมเดียวกันสองครั้งอาจให้ Order ต่างกัน เมื่อ Order มีความสำคัญ (Tests, Playground การเรียนรู้, Logging) ให้ Sort Key ก่อน:

let mut keys: Vec<&String> = scores.keys().collect();
keys.sort();
for k in keys {
println!("{}: {}", k, scores[k]);
}
scores.remove("Bob");
println!("Bob present: {}", scores.contains_key("Bob"));
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<String, u32> = HashMap::new();
scores.insert(String::from("Alice"), 100);
scores.insert(String::from("Bob"), 85);
scores.insert(String::from("Carol"), 92);
// entry API: insert if absent
scores.entry(String::from("Dave")).or_insert(70);
// Alice already exists — or_insert does nothing
scores.entry(String::from("Alice")).or_insert(0);
// get returns Option<&V>
if let Some(score) = scores.get("Alice") {
println!("Alice scored {}", score);
}
// deterministic iteration: sort keys
let mut keys: Vec<&String> = scores.keys().collect();
keys.sort();
for k in keys {
println!("{}: {}", k, scores[k]);
}
// remove
scores.remove("Bob");
println!("Bob present: {}", scores.contains_key("Bob"));
}
scores.get("Alice") คืนค่าอะไรเมื่อ Alice ไม่อยู่ใน Map?
entry(key).or_insert(v) ทำอะไรเมื่อ Key มีอยู่แล้ว?
ทำไม Order การ Iterate ของ HashMap ใน Rust จึงไม่ Deterministic?
ประเภทต้อง Implement Trait Bound ใดเพื่อใช้เป็น Key ของ HashMap?