Chủ đề Rust quan trọng
Rust HashMap
Store values under keys and look them up fast: insert, get, entry and counting.
Bạn sẽ học được gì
- 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.
Những điểm quan trọng
- get returns an Option: the key may be missing.
entry(key).or_insert(0) is the counting pattern.- A HashMap has no fixed order.
Ví dụ Rust chạy được
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"]Luyện tập
Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.
Bạn học xong bài này chưa?
Đánh dấu đã học để theo dõi tiến độ của bạn.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
- Tần suất ký tự Đếm số lần xuất hiện của mỗi ký tự. Dễ
- Ký Tự Độc Nhất Đầu Tiên Tìm ký tự đầu tiên chỉ xuất hiện một lần. Dễ