Skip to content
เข้าสู่ระบบ

Collections - โครงสร้างข้อมูล

นอกจาก Vec แล้ว Rust มี Collections อื่นๆ ให้เลือกใช้ตามความเหมาะสม!

เลือก Collection ไหนดี?

Section titled “เลือก Collection ไหนดี?”
ต้องการใช้O(operation)
เรียงลำดับ, indexVec<T>O(1) access
key-valueHashMap<K, V>O(1) avg
ไม่ซ้ำHashSet<T>O(1) avg
เรียงลำดับ keyBTreeMap<K, V>O(log n)
เรียงลำดับ ไม่ซ้ำBTreeSet<T>O(log n)
เพิ่ม/ลบหัวท้ายVecDeque<T>O(1)
ค่าสูงสุดก่อนBinaryHeap<T>O(log n)
use std::collections::HashMap;
fn main() {
// สร้าง HashMap
let mut scores = HashMap::new();
// เพิ่มข้อมูล
scores.insert("Alice", 95);
scores.insert("Bob", 87);
scores.insert("Charlie", 92);
println!("scores: {:?}", scores);
// เข้าถึง (return Option)
let alice_score = scores.get("Alice");
println!("Alice: {:?}", alice_score); // Some(&95)
// ตรวจว่ามี key ไหม
println!("has Alice: {}", scores.contains_key("Alice"));
// ลบ
let removed = scores.remove("Bob");
println!("removed Bob: {:?}", removed);
// วนซ้ำ
println!("=== ทุกคน ===");
for (name, score) in &scores {
println!("{}: {}", name, score);
}
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด