26. HashMap

  • 理解 HashMap<K, V> 的作用和基本用法。
  • 掌握插入、访问、更新和遍历键值对。
  • 理解 HashMap 与所有权的关系。
  • 了解键类型需要满足 Eq 和 Hash trait 的要求。 ## 26.1 什么是 HashMap<K, V>

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

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

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

snippet.rust
use std::collections::HashMap;
 
let mut scores = HashMap::new();
 
scores.insert(String::from("Alice"), 95);
scores.insert(String::from("Bob"), 87);
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();
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}
snippet.rust
scores.insert(String::from("Alice"), 100);
snippet.rust
let count = scores.entry(String::from("Alice")).or_insert(0);
*count += 5;
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);
}

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

当插入 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 已被移动

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

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);
操作 方法 说明
创建 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 顺序不保证
  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. 写一个函数,接收一段文本,统计每个单词出现的次数。

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • rust/hashmap.txt
  • 最后更改: 2026/08/12 23:39
  • 由 张叶安