显示页面讨论过去修订反向链接回到顶部 本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。 # 26. HashMap ## 学习目标 - 理解 `HashMap<K, V>` 的作用和基本用法。 - 掌握插入、访问、更新和遍历键值对。 - 理解 `HashMap` 与所有权的关系。 - 了解键类型需要满足 `Eq` 和 `Hash` trait 的要求。 ## 26.1 什么是 `HashMap<K, V>` `HashMap<K, V>` 是 Rust 标准库提供的**哈希表**,用于存储键值对。它通过键来快速查找对应的值。 ```rust use std::collections::HashMap; ``` `HashMap` 不在标准库 prelude 中,需要手动引入。 ## 26.2 创建 `HashMap` ```rust use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Alice"), 95); scores.insert(String::from("Bob"), 87); ``` ### 从两个 `Vec` 创建 ```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` ```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` 用于处理键不存在的情况: ```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 更新值 ### 覆盖旧值 ```rust scores.insert(String::from("Alice"), 100); ``` ### 基于旧值更新 ```rust let count = scores.entry(String::from("Alice")).or_insert(0); *count += 5; ``` ## 26.5 遍历 `HashMap` ```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` 中: ```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`)都满足要求。自定义类型需要手动实现。 ```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. 下面代码为什么会报错?如何修改? ```rust let mut map = HashMap::new(); map.insert("a", 1); let value = map.get("a"); map.insert("b", 2); println!("{}", value.unwrap()); ``` 2. `entry` 模式相比 `insert` 有什么优势? 3. 写一个函数,接收一段文本,统计每个单词出现的次数。 登录 Detach Close 该主题尚不存在 您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。 rust/hashmap.txt 最后更改: 2026/08/12 23:39由 张叶安 登录