From eba015c0bb73d5cab8304b3f5aa3d0eddb755bb3 Mon Sep 17 00:00:00 2001 From: Kato0130 <106635619+0130w@users.noreply.github.com> Date: Thu, 14 Sep 2023 14:09:16 -0400 Subject: [PATCH] add Rust codes for hash_map (#751) --- docs/chapter_hashing/hash_map.md | 33 ++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/chapter_hashing/hash_map.md b/docs/chapter_hashing/hash_map.md index 9f1b9b523..6d10503bd 100755 --- a/docs/chapter_hashing/hash_map.md +++ b/docs/chapter_hashing/hash_map.md @@ -239,7 +239,26 @@ === "Rust" ```rust title="hash_map.rs" + use std::collections::HashMap; + + /* 初始化哈希表 */ + let mut map: HashMap = HashMap::new(); + + /* 添加操作 */ + // 在哈希表中添加键值对 (key, value) + map.insert(12836, "小哈".to_string()); + map.insert(15937, "小啰".to_string()); + map.insert(16750, "小算".to_string()); + map.insert(13279, "小法".to_string()); + map.insert(10583, "小鸭".to_string()); + /* 查询操作 */ + // 向哈希表中输入键 key ,得到值 value + let _name: Option<&String> = map.get(&15937); + + /* 删除操作 */ + // 在哈希表中删除键值对 (key, value) + let _removed_value: Option = map.remove(&10583); ``` === "C" @@ -420,7 +439,21 @@ === "Rust" ```rust title="hash_map.rs" + /* 遍历哈希表 */ + // 遍历键值对 Key->Value + for (key, value) in &map { + println!("{key} -> {value}"); + } + + // 单独遍历键 Key + for key in map.keys() { + println!("{key}"); + } + // 单独遍历值 Value + for value in map.values() { + println!("{value}"); + } ``` === "C"