HashMap<K, V> 的作用和基本用法。HashMap 与所有权的关系。Eq 和 Hash trait 的要求。
## 26.1 什么是 HashMap<K, V>
HashMap<K, V> 是 Rust 标准库提供的哈希表,用于存储键值对。它通过键来快速查找对应的值。
use std::collections::HashMap;
HashMap 不在标准库 prelude 中,需要手动引入。
use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Alice"), 95); scores.insert(String::from("Bob"), 87);
use std::collections::HashMap; let names = vec![String::from("Alice"), String::from("Bob")]; let scores = vec![95, 87]; let mut map: HashMap<_, _> = names.into_iter().zip(scores.into_iter()).collect();
use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Alice"), 95); let score = scores.get("Alice"); println!("{:?}", score); // Some(95)
get 返回 Option<&V>,键不存在时返回 None。
entry 用于处理键不存在的情况:
use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Alice"), 95); scores.entry(String::from("Alice")).or_insert(0); scores.entry(String::from("Bob")).or_insert(0); println!("{:?}", scores); // {"Alice": 95, "Bob": 0}
scores.insert(String::from("Alice"), 100);
let count = scores.entry(String::from("Alice")).or_insert(0); *count += 5;
use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Alice"), 95); scores.insert(String::from("Bob"), 87); for (key, value) in &scores { println!("{}: {}", key, value); }
遍历顺序不保证与插入顺序一致。
当插入 String 等拥有所有权的类型时,键和值会被移动到 HashMap 中:
use std::collections::HashMap; let key = String::from("color"); let value = String::from("blue"); let mut map = HashMap::new(); map.insert(key, value); // println!("{}", key); // 错误:key 已被移动
如果想保留原变量,可以使用引用,但键和值的生命周期必须受到限制。
HashMap 的键类型必须实现 Eq 和 Hash trait。基本类型(如 i32、String、&str)都满足要求。自定义类型需要手动实现。
use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); // &str 可以作为键 map.insert("b", 2);
| 操作 | 方法 | 说明 |
| 创建 | HashMap::new() | 需要 use std::collections::HashMap |
| 插入 | map.insert(k, v) | 键和值会被移动 |
| 访问 | map.get(&k) | 返回 Option<&V> |
| 不存在时插入 | map.entry(k).or_insert(v) | 返回 &mut V |
| 覆盖 | map.insert(k, v) | 新值覆盖旧值 |
| 遍历 | for (k, v) in &map | 顺序不保证 |
let mut map = HashMap::new(); map.insert("a", 1); let value = map.get("a"); map.insert("b", 2); println!("{}", value.unwrap());
entry 模式相比 insert 有什么优势?