学习Rust第14天:HashMaps

今天我们来看看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 counts
    let mut word_count = HashMap::new();

    // Iterate over each word in the text
    for word in text.split_whitespace() {
        // Count the occurrences of each word
        let count = word_count.entry(word).or_insert(0);
        *count += 1;
    }

    // Print the word counts
    for (word, count) in &word_count {
        println!("{}: {}", word, count);
    }
}
  • We import HashMap from the std::collections module to use hashmaps in our program.
    我们从 std::collections 模块导入 HashMap ,以便在程序中使用hashmaps。

In the main function: 在 main 函数中:

  • We define a string text containing the input text.
    我们定义一个包含输入文本的字符串 text 。
  • We create an empty hashmap named word_count to 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 entry method of the HashMap to get an Entry for the word. This method returns an enum Entry that represents a reference to a hashmap entry.
    我们使用 HashMap 的 entry 方法来获得单词的 Entry 。这个方法返回一个enum Entry ,它表示对hashmap条目的引用。
  • We use the or_insert method on the Entry to insert a new entry with a value of 0 if 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 += 1 operator.
    然后,我们通过解引用可变引用并使用 += 1 操作符来增加单词的计数。
  • After counting all the words, we iterate over the word_count hashmap using a for loop. For each key-value pair, we print the word and its count.
    在计算完所有单词后,我们使用 for 循环遍历 word_count hashmap。对于每个键值对,我们打印单词及其计数。

This program will output :
该程序将输出:

hello: 2
world: 2
rust: 1

相关推荐

  1. 学习 Rust十四:如何使用HashMap

    2024-04-26 15:36:03       34 阅读
  2. 学习 Rust 16 :泛型类型

    2024-04-26 15:36:03       36 阅读
  3. [rustlings]11_hashmaps

    2024-04-26 15:36:03       24 阅读
  4. 30拿下RustHashMap

    2024-04-26 15:36:03       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-26 15:36:03       91 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-26 15:36:03       97 阅读
  3. 在Django里面运行非项目文件

    2024-04-26 15:36:03       78 阅读
  4. Python语言-面向对象

    2024-04-26 15:36:03       88 阅读

热门阅读

  1. Go语言第二篇-基本数据类型与转义字符

    2024-04-26 15:36:03       35 阅读
  2. 多路IO复用--epoll

    2024-04-26 15:36:03       45 阅读
  3. python笔记(15)函数

    2024-04-26 15:36:03       83 阅读
  4. WPF之RadioButton单选框和checkbox多选框

    2024-04-26 15:36:03       37 阅读
  5. MyBatis笔记——一对多参映射问题解决

    2024-04-26 15:36:03       34 阅读