หัวข้อสำคัญของ Rust
Rust HashMap
Store values under keys and look them up fast: insert, get, entry and counting.
สิ่งที่คุณจะได้เรียนรู้
- insert and get
- entry().or_insert()
- Sorting the keys
stock
"apple"5"pear"5"plum"1Values found by key
A HashMap<K, V> stores values under keys, so you can find a value quickly by its key. It is Rust's version of a dictionary or associative array.
insert adds or replaces a value. entry(key).or_insert(0) returns the existing value or inserts a default, which makes counting easy. get returns an Option because the key may be missing. A HashMap has no fixed order, so the keys are sorted before printing.
ประเด็นสำคัญ
- get returns an Option: the key may be missing.
entry(key).or_insert(0) is the counting pattern.- A HashMap has no fixed order.
ตัวอย่าง Rust ที่รันได้
Rust
main.rs
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert(String::from("apple"), 3);
stock.insert(String::from("pear"), 5);
*stock.entry(String::from("apple")).or_insert(0) += 2;
stock.entry(String::from("plum")).or_insert(1);
println!("apples: {}", stock["apple"]);
println!("has kiwi: {}", stock.contains_key("kiwi"));
if let Some(count) = stock.get("pear") {
println!("pears: {count}");
}
let mut names: Vec<&String> = stock.keys().collect();
names.sort();
println!("{:?}", names);
}
apples: 5
has kiwi: false
pears: 5
["apple", "pear", "plum"]ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- ความถี่ของตัวอักษร นับจำนวนครั้งที่ตัวอักษรแต่ละตัวปรากฏขึ้น ง่าย
- ตัวอักษรที่ไม่ซ้ำตัวแรก หาตัวอักษรตัวแรกที่ปรากฏเพียงครั้งเดียว ง่าย