今天我们来看看Rust中的hashmaps,在 std::collections crate中可用,是存储键值对的有效数据结构。本文介绍了创建、插入、访问、更新和迭代散列表等基本操作。通过一个计算单词出现次数的实际例子,我们展示了它们在现实世界中的实用性。Hashmaps提供了一种灵活而强大的组织和访问数据的方法,使其成为Rust编程中不可或缺的工具。

Introduction 介绍
Hashmaps store key value pairs and to use a hashing function to know where to put a key/value.
哈希映射存储键值对,并使用哈希函数来知道在哪里放置键/值。
Hashmaps are a part of the std::collections crate.
Hashmaps是 std::collections crate的一部分。
Creation 创作
Just like a vector or a string we can use the new() method for hashmaps.
就像向量或字符串一样,我们可以使用hashmaps的 new() 方法。
use std::collections::HashMap;fn main(){let mut my_map = HashMap::new();
} Insertion 插入
we can insert key-value pairs into a hashmap using the insert method
我们可以使用 insert 方法将键值对插入到hashmap中
use std::collections::HashMap;fn main(){let mut my_map = HashMap::new();my_map.insert("key", "value");
} Accessing 访问
We can access values in a hashmap using the get method, which returns an Option<&V>:
我们可以使用 get 方法访问hashmap中的值,该方法返回 Option<&V> :
use std::collections::HashMap;fn main(){let mut my_map = HashMap::new();my_map.insert("key", "value");if let Some(value) = my_map.get("key") {println!("Value: {}", value);} else {println!("Key not found");}} Update 更新
We can update the value associated with a key using the insert method, which will replace the existing value if the key already exists:
我们可以使用 insert 方法更新与键关联的值,如果键已经存在,该方法将替换现有值:
use std::collections::HashMap;fn main(){let mut my_map = HashMap::new();my_map.insert("key", "value");if let Some(value) = my_map.get("key") {println!("Value: {}", value);} else {println!("Key not found");}my_map.insert("key", "new_value");
} If we don’t want to overwrite existing values, we can use this
如果我们不想覆盖现有的值,我们可以使用
my_map.entry("key").or_insert("another_key_value_pair"); If key exists this line of code will not make any changes to the hashmap but if it does not exist it will create a key-value pair that looks something like this
如果 key 存在,这行代码将不会对散列表进行任何更改,但如果它不存在,它将创建一个类似于以下内容的键值对
{"key":"another_key_value_pair"} The method entry gives us an entry enum which represents the value we provided in the brackets. Then we call the or_insert method which inserts a key-value pair if this already does not exist.
方法 entry 给了我们一个条目枚举,它表示我们在括号中提供的值。然后我们调用 or_insert 方法,如果键-值对不存在,则插入键-值对。
Iteration 迭代
We can iterate over the key-value pairs in a hashmap using a for loop or an iterator
我们可以使用 for 循环或迭代器遍历hashmap中的键值对
use std::collections::HashMap;fn main(){let mut my_map = HashMap::new();my_map.insert("key", "value");if let Some(value) = my_map.get("key") {println!("Value: {}", value);} else {println!("Key not found");}my_map.insert("key", "new_value");for (key, value) in &my_map {println!("Key: {}, Value: {}", key, value);}
} Size 大小
We can get the number of key-value pairs in a hashmap using the len method:
我们可以使用 len 方法来获得hashmap中的键值对的数量:
println!("Size: {}", my_map.len()); Example 例如
use std::collections::HashMap;fn main() {let text = "hello world hello rust world";// Create an empty hashmap to store word countslet mut word_count = HashMap::new();// Iterate over each word in the textfor word in text.split_whitespace() {// Count the occurrences of each wordlet count = word_count.entry(word).or_insert(0);*count += 1;}// Print the word countsfor (word, count) in &word_count {println!("{}: {}", word, count);}
} - We import
HashMapfrom thestd::collectionsmodule to use hashmaps in our program.
我们从std::collections模块导入HashMap,以便在程序中使用hashmaps。
In the main function: 在 main 函数中:
- We define a string
textcontaining the input text.
我们定义一个包含输入文本的字符串text。 - We create an empty hashmap named
word_countto store the counts of each word.
我们创建一个名为word_count的空散列表来存储每个单词的计数。 - We iterate over each word in the input text using
split_whitespace(), which splits the text into words based on whitespace.
我们使用split_whitespace()来覆盖输入文本中的每个单词,它基于空格将文本拆分为单词。
For each word: 对于每个单词:
- We use the
entrymethod of theHashMapto get anEntryfor the word. This method returns an enumEntrythat represents a reference to a hashmap entry.
我们使用HashMap的entry方法来获得单词的Entry。这个方法返回一个enumEntry,它表示对hashmap条目的引用。 - We use the
or_insertmethod on theEntryto insert a new entry with a value of0if the word does not exist in the hashmap. Otherwise, it returns a mutable reference to the existing value.
我们在Entry上使用or_insert方法来插入一个值为0的新条目,如果这个单词在hashmap中不存在的话。否则,它返回对现有值的可变引用。 - We then increment the count of the word by dereferencing the mutable reference and using the
+= 1operator.
然后,我们通过解引用可变引用并使用+= 1操作符来增加单词的计数。 - After counting all the words, we iterate over the
word_counthashmap using aforloop. For each key-value pair, we print the word and its count.
在计算完所有单词后,我们使用for循环遍历word_counthashmap。对于每个键值对,我们打印单词及其计数。
This program will output :
该程序将输出:
hello: 2
world: 2
rust: 1