Rust 语言学习手册

免费学习 系统级编程 内存安全

Rust学习手册《HashMap 与 HashSet》:`HashMap` 是键值对哈希表,`HashSet` 是基于 `HashMap` 的集合。 **HashMap:** ```rust use std::collections::HashMap; let mut scores = Has...

集合类型

HashMap 与 HashSet

【详细说明 & 代码示例】
`HashMap` 是键值对哈希表,`HashSet` 是基于 `HashMap` 的集合。 **HashMap:** ```rust use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); let score = scores.get(&String::from("Blue")); // Option // 遍历 for (key, value) in &scores { println!("{}: {}", key, value); } // 更新 scores.entry(String::from("Blue")).or_insert(20); ``` **HashSet:** ```rust use std::collections::HashSet; let mut set = HashSet::new(); set.insert(1); set.insert(2); if set.contains(&1) { println!("has 1"); } ``` **注意:** 键类型需实现 `Eq` 和 `Hash`。默认使用 SipHash 抗冲突。

学习提示:建议安装 Rust 工具链(rustup),使用 cargo 构建项目,并熟悉 rustc 编译器错误信息(Rust 的报错非常详细友好)。

全部章节目录(共 63 个知识点)

Rust 基础 (1个知识点)

所有权系统 (1个知识点)

借用与引用 (1个知识点)

生命周期 (1个知识点)

Cargo 与工具链 (2个知识点)

使用说明

  • • 本手册涵盖 Rust 从基础到并发、异步、Web 开发的完整知识体系
  • • 在搜索框输入关键词,快速定位相关知识点
  • • 点击条目标题进入详情页,查看详细说明与代码示例
  • • 页面按分类展示所有知识点,方便系统性学习
  • • 建议通过 Rust 官方文档(doc.rust-lang.org)加深理解