目录

26. HashMap

学习目标

HashMap<K, V> 是 Rust 标准库提供的哈希表,用于存储键值对。它通过键来快速查找对应的值。

snippet.rust
use std::collections::HashMap;

HashMap 不在标准库 prelude 中,需要手动引入。

26.2 创建 `HashMap`

snippet.rust
use std::collections::HashMap;
 
let mut scores = HashMap::new();
 
scores.insert(String::from("Alice"), 95);
scores.insert(String::from("Bob"), 87);

从两个 `Vec` 创建

snippet.rust
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();

26.3 访问值

使用 `get`

snippet.rust
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` 模式

entry 用于处理键不存在的情况:

snippet.rust
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}

26.4 更新值

覆盖旧值

snippet.rust
scores.insert(String::from("Alice"), 100);

基于旧值更新

snippet.rust
let count = scores.entry(String::from("Alice")).or_insert(0);
*count += 5;

26.5 遍历 `HashMap`

snippet.rust
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);
}

遍历顺序不保证与插入顺序一致。

26.6 所有权与 `HashMap`

当插入 String 等拥有所有权的类型时,键和值会被移动到 HashMap 中:

snippet.rust
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 已被移动

如果想保留原变量,可以使用引用,但键和值的生命周期必须受到限制。

26.7 键类型要求

HashMap 的键类型必须实现 Eq 和 Hash trait。基本类型(如 i32、String、&str)都满足要求。自定义类型需要手动实现。

snippet.rust
use std::collections::HashMap;
 
let mut map = HashMap::new();
map.insert("a", 1);                 // &str 可以作为键
map.insert("b", 2);

26.8 小结

操作 方法 说明
创建 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 顺序不保证

26.9 思考题

  1. 下面代码为什么会报错?如何修改?
snippet.rust
let mut map = HashMap::new();
map.insert("a", 1);
let value = map.get("a");
map.insert("b", 2);
println!("{}", value.unwrap());
  1. entry 模式相比 insert 有什么优势?
  2. 写一个函数,接收一段文本,统计每个单词出现的次数。