3.7 `HashMap`
07-
HashMap — Comprehensive Rust2 分钟阅读
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/std-types/hashmap.html
3.7 HashMap
带 HashDoS 攻击防护的标准哈希映射:
| |
HashMap不在 prelude 中,需要引入作用域。试一下下面几行代码。第一行会查看书是否在哈希映射中,若不在则返回替代值。第二行会在找不到该书时把替代值插入哈希映射。
1 2 3 4 5 6 7 8 9// Copyright 2023 Google LLC // SPDX-License-Identifier: Apache-2.0 # let pc1 = page_counts .get("Harry Potter and the Sorcerer's Stone") .unwrap_or(&336); let pc2 = page_counts .entry("The Hunger Games") .or_insert(374);与
vec!不同,遗憾的是没有标准的hashmap!宏。
不过自 Rust 1.56 起,HashMap 实现了
From<[(K, V); N]>, 这让我们可以轻松从字面量数组初始化哈希映射:
1 2 3 4 5 6 7// Copyright 2023 Google LLC // SPDX-License-Identifier: Apache-2.0 # let page_counts = HashMap::from([ ("Harry Potter and the Sorcerer's Stone".to_string(), 336), ("The Hunger Games".to_string(), 374), ]);或者,HashMap 可以从任何产生键值元组的
Iterator构建。该类型有若干「方法专用」的返回类型,例如
std::collections::hash_map::Keys。搜索 Rust 文档时这些类型经常出现。向学员展示该类型的文档,以及返回到keys方法的有用链接。